Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
29.50% covered (danger)
29.50%
852 / 2888
3.64% covered (danger)
3.64%
2 / 55
CRAP
0.00% covered (danger)
0.00%
0 / 1
AppController
29.45% covered (danger)
29.45%
850 / 2886
3.64% covered (danger)
3.64%
2 / 55
329967.36
0.00% covered (danger)
0.00%
0 / 1
 processSGF
73.58% covered (warning)
73.58%
39 / 53
0.00% covered (danger)
0.00%
0 / 1
19.15
 xFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 yFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 getInitialPositionEnd
62.50% covered (warning)
62.50%
5 / 8
0.00% covered (danger)
0.00%
0 / 1
3.47
 getInitialPosition
50.00% covered (danger)
50.00%
10 / 20
0.00% covered (danger)
0.00%
0 / 1
10.50
 getInvisibleSets
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 getDeletedSets
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 startPageUpdate
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
5.03
 uotd
0.00% covered (danger)
0.00%
0 / 157
0.00% covered (danger)
0.00%
0 / 1
2070
 deleteUnusedStatuses
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
72
 saveSolvedNumber
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
156
 convertEloToXp
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 resetUserElos
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 getNewElo
58.23% covered (warning)
58.23%
46 / 79
0.00% covered (danger)
0.00%
0 / 1
57.28
 handleContribution
52.94% covered (warning)
52.94%
9 / 17
0.00% covered (danger)
0.00%
0 / 1
2.42
 getAllTags
82.76% covered (warning)
82.76%
24 / 29
0.00% covered (danger)
0.00%
0 / 1
7.25
 userRefresh
0.00% covered (danger)
0.00%
0 / 155
0.00% covered (danger)
0.00%
0 / 1
992
 deleteUserBoards
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 halfXP
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
 getNewTsumego
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 publishSingle
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
30
 getTsumegoOfTheDay
0.00% covered (danger)
0.00%
0 / 104
0.00% covered (danger)
0.00%
0 / 1
1190
 ratingMatch
0.00% covered (danger)
0.00%
0 / 62
0.00% covered (danger)
0.00%
0 / 1
992
 rating2
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
132
 encrypt
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 decrypt
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 checkPictureLarge
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 checkPicture
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 getTsumegoRankx
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
506
 adjustElo
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
132
 getTsumegoElo
11.32% covered (danger)
11.32%
6 / 53
0.00% covered (danger)
0.00%
0 / 1
746.11
 getTsumegoRankVal
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
506
 getTsumegoRankMax
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
506
 saveDanSolveCondition
5.56% covered (danger)
5.56%
1 / 18
0.00% covered (danger)
0.00%
0 / 1
48.28
 updateSprintCondition
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
4.00
 updateGoldenCondition
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
12
 setPotionCondition
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 updateGems
3.85% covered (danger)
3.85%
4 / 104
0.00% covered (danger)
0.00%
0 / 1
2183.48
 checkProblemNumberAchievements
42.39% covered (danger)
42.39%
39 / 92
0.00% covered (danger)
0.00%
0 / 1
166.38
 checkDanSolveAchievements
46.24% covered (danger)
46.24%
80 / 173
0.00% covered (danger)
0.00%
0 / 1
561.73
 checkForLocked
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 checkNoErrorAchievements
69.23% covered (warning)
69.23%
45 / 65
0.00% covered (danger)
0.00%
0 / 1
25.42
 checkTimeModeAchievements
35.40% covered (danger)
35.40%
40 / 113
0.00% covered (danger)
0.00%
0 / 1
2273.83
 checkRatingAchievements
54.44% covered (warning)
54.44%
49 / 90
0.00% covered (danger)
0.00%
0 / 1
95.92
 checkLevelAchievements
41.11% covered (danger)
41.11%
37 / 90
0.00% covered (danger)
0.00%
0 / 1
175.88
 checkSetCompletedAchievements
19.72% covered (danger)
19.72%
14 / 71
0.00% covered (danger)
0.00%
0 / 1
166.54
 setAchievementSpecial
0.00% covered (danger)
0.00%
0 / 184
0.00% covered (danger)
0.00%
0 / 1
4160
 checkSetAchievements
0.00% covered (danger)
0.00%
0 / 221
0.00% covered (danger)
0.00%
0 / 1
4556
 getXPJump
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
72
 getHealth
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
462
 updateXP
75.00% covered (warning)
75.00%
36 / 48
0.00% covered (danger)
0.00%
0 / 1
18.52
 getPartitionRange
68.18% covered (warning)
68.18%
15 / 22
0.00% covered (danger)
0.00%
0 / 1
8.58
 handleSearchSettings
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 signIn
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 beforeFilter
83.48% covered (warning)
83.48%
283 / 339
0.00% covered (danger)
0.00%
0 / 1
95.37
 afterFilter
n/a
0 / 0
n/a
0 / 0
1
1<?php
2
3App::uses('Auth', 'Utility');
4App::uses('SearchParameters', 'Utility');
5
6class AppController extends Controller {
7    public $viewClass = 'App';
8
9    public $components = [
10        'Session',
11        //'DebugKit.Toolbar',
12        'Flash',
13        'PlayResultProcessor',
14        'TimeMode',
15    ];
16
17    public static function processSGF($sgf) {
18        $aw = strpos($sgf, 'AW');
19        $ab = strpos($sgf, 'AB');
20        $boardSizePos = strpos($sgf, 'SZ');
21        $boardSize = 19;
22        $sgfArr = str_split($sgf);
23        if ($boardSizePos !== false) {
24            $boardSize = $sgfArr[$boardSizePos + 3] . '' . $sgfArr[$boardSizePos + 4];
25        }
26        if (substr($boardSize, 1) == ']') {
27            $boardSize = substr($boardSize, 0, 1);
28        }
29
30        $black = AppController::getInitialPosition($ab, $sgfArr, 'x');
31        $white = AppController::getInitialPosition($aw, $sgfArr, 'o');
32        $stones = array_merge($black, $white);
33
34        $board = [];
35        for ($i = 0; $i < 19; $i++) {
36            $board[$i] = [];
37            for ($j = 0; $j < 19; $j++) {
38                $board[$i][$j] = '-';
39            }
40        }
41        $lowestX = 18;
42        $lowestY = 18;
43        $highestX = 0;
44        $highestY = 0;
45        $stonesCount = count($stones);
46        for ($i = 0; $i < $stonesCount; $i++) {
47            if ($stones[$i][0] < $lowestX) {
48                $lowestX = $stones[$i][0];
49            }
50            if ($stones[$i][0] > $highestX) {
51                $highestX = $stones[$i][0];
52            }
53            if ($stones[$i][1] < $lowestY) {
54                $lowestY = $stones[$i][1];
55            }
56            if ($stones[$i][1] > $highestY) {
57                $highestY = $stones[$i][1];
58            }
59        }
60        if (18 - $lowestX < $lowestX) {
61            $stones = AppController::xFlip($stones);
62        }
63        if (18 - $lowestY < $lowestY) {
64            $stones = AppController::yFlip($stones);
65        }
66        $highestX = 0;
67        $highestY = 0;
68        $stonesCount = count($stones);
69        for ($i = 0; $i < $stonesCount; $i++) {
70            if ($stones[$i][0] > $highestX) {
71                $highestX = $stones[$i][0];
72            }
73            if ($stones[$i][1] > $highestY) {
74                $highestY = $stones[$i][1];
75            }
76            $board[$stones[$i][0]][$stones[$i][1]] = $stones[$i][2];
77        }
78        $tInfo = [];
79        $tInfo[0] = $highestX;
80        $tInfo[1] = $highestY;
81        $arr = [];
82        $arr[0] = $board;
83        $arr[1] = $stones;
84        $arr[2] = $tInfo;
85        $arr[3] = $boardSize;
86
87        return $arr;
88    }
89
90    public static function xFlip($stones) {
91        $stonesCount = count($stones);
92        for ($i = 0; $i < $stonesCount; $i++) {
93            $stones[$i][0] = 18 - $stones[$i][0];
94        }
95
96        return $stones;
97    }
98
99    public static function yFlip($stones) {
100        $stonesCount = count($stones);
101        for ($i = 0; $i < $stonesCount; $i++) {
102            $stones[$i][1] = 18 - $stones[$i][1];
103        }
104
105        return $stones;
106    }
107
108    public static function getInitialPositionEnd($pos, $sgfArr) {
109        $endCondition = 0;
110        $currentPos1 = $pos + 2;
111        $currentPos2 = $pos + 5;
112        while ($sgfArr[$currentPos1] == '[' && $sgfArr[$currentPos2] == ']') {
113            $endCondition = $currentPos2;
114            $currentPos1 += 4;
115            $currentPos2 += 4;
116        }
117
118        return $endCondition;
119    }
120
121    public static function getInitialPosition($pos, $sgfArr, $color) {
122        $arr = [];
123        $end = AppController::getInitialPositionEnd($pos, $sgfArr);
124        for ($i = $pos + 2; $i < $end; $i++) {
125            if ($sgfArr[$i] != '[' && $sgfArr[$i] != ']') {
126                array_push($arr, strtolower($sgfArr[$i]));
127            }
128        }
129        $alphabet = array_flip(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']);
130        $xy = true;
131        $arr2 = [];
132        $c = 0;
133        $arrCount = count($arr);
134        for ($i = 0; $i < $arrCount; $i++) {
135            $arr[$i] = $alphabet[$arr[$i]];
136            if ($xy) {
137                $arr2[$c] = [];
138                $arr2[$c][0] = $arr[$i];
139            } else {
140                $arr2[$c][1] = $arr[$i];
141                $arr2[$c][2] = $color;
142                $c++;
143            }
144            $xy = !$xy;
145        }
146
147        return $arr2;
148    }
149
150    protected function getInvisibleSets() {
151        $this->loadModel('Set');
152        $invisibleSets = [];
153        $in = $this->Set->find('all', ['conditions' => ['public' => 0]]);
154        if (!$in) {
155            $in = [];
156        }
157        foreach ($in as $item) {
158            $invisibleSets[] = $item['Set']['id'];
159        }
160
161        return $invisibleSets;
162    }
163
164    protected function getDeletedSets() {
165        $dSets = [];
166        $de = $this->Set->find('all', ['conditions' => ['public' => -1]]);
167        if (!$de) {
168            $de = [];
169        }
170        foreach ($de as $item) {
171            $dSets[] = $item['Set']['id'];
172        }
173
174        return $dSets;
175    }
176
177    /**
178     * @return void
179     */
180    public static function startPageUpdate() {
181        $str = '';
182        $latest = ClassRegistry::init('AchievementStatus')->find('all', ['limit' => 7, 'order' => 'created DESC']);
183        if (!$latest) {
184            $latest = [];
185        }
186        $latestCount = count($latest);
187        for ($i = 0; $i < $latestCount; $i++) {
188            $a = ClassRegistry::init('Achievement')->findById($latest[$i]['AchievementStatus']['achievement_id']);
189            $u = ClassRegistry::init('User')->findById($latest[$i]['AchievementStatus']['user_id']);
190            if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
191                $startPageUser = AppController::checkPicture($u);
192            } else {
193                $startPageUser = $u['User']['name'];
194            }
195            $latest[$i]['AchievementStatus']['name'] = $a['Achievement']['name'];
196            $latest[$i]['AchievementStatus']['color'] = $a['Achievement']['color'];
197            $latest[$i]['AchievementStatus']['image'] = $a['Achievement']['image'];
198            $latest[$i]['AchievementStatus']['user'] = $startPageUser;
199            $str .= '<div class="quote1"><div class="quote1a"><a href="/achievements/view/' . $a['Achievement']['id'] . '"><img src="/img/' . $a['Achievement']['image'] . '.png" width="34px"></a></div>';
200            $str .= '<div class="quote1b">Achievement gained by ' . $startPageUser . ':<br><div class=""><b>' . $a['Achievement']['name'] . '</b></div></div></div>';
201        }
202        file_put_contents('mainPageAjax.txt', $str);
203    }
204
205    /**
206     * @return void
207     */
208    protected function uotd() { //routine1
209        $this->loadModel('User');
210        $this->loadModel('DayRecord');
211        $this->loadModel('TsumegoAttempt');
212        $this->loadModel('Achievement');
213        $this->loadModel('AchievementCondition');
214        $today = date('Y-m-d');
215        $ux2 = $this->User->find('all', [
216            'limit' => '8',
217            'order' => 'reuse3 DESC',
218            'conditions' => [
219                'NOT' => ['id' => [33]],
220            ],
221        ]);
222        if (!$ux2) {
223            $ux2 = [];
224        }
225        $last = $this->DayRecord->find('all', ['limit' => '7', 'order' => 'date DESC']);
226        if (!$last) {
227            $last = [];
228        }
229        $lastUotds = [];
230        $lastUsers = [];
231        foreach ($last as $item) {
232            $lastUotds[] = $item['DayRecord']['user_id'];
233        }
234        foreach ($ux2 as $item) {
235            $lastUsers[] = $item['User']['id'];
236        }
237        $resultUser = 72;
238        $lastUsersCount = count($lastUsers);
239        for ($i = 0; $i < $lastUsersCount; $i++) {
240            $foundUser = false;
241            $lastUotdsCount = count($lastUotds);
242            for ($j = 0; $j < $lastUotdsCount; $j++) {
243                if ($lastUsers[$i] == $lastUotds[$j]) {
244                    $foundUser = true;
245                }
246            }
247            if (!$foundUser) {
248                $resultUser = $lastUsers[$i];
249
250                break;
251            }
252        }
253        $ux = $this->User->findById($resultUser);
254
255        $recentlyUsed = [];
256        $d = 1;
257        while ($d <= 10) {
258            $ru = $this->DayRecord->find('first', ['conditions' => ['date' => date('Y-m-d', strtotime('-' . $d . ' days'))]]);
259            if ($ru) {
260                array_push($recentlyUsed, $ru);
261            }
262            $d++;
263        }
264        $currentQuote = 'q01';
265        $newQuote = 'q01';
266        $quoteChosen = false;
267        while (!$quoteChosen) {
268            $newQuote = rand(1, 45);
269            if ($newQuote < 10) {
270                $newQuote = 'q0' . $newQuote;
271            } else {
272                $newQuote = 'q' . $newQuote;
273            }
274
275            $f = false;
276            $recentlyUsedCount = count($recentlyUsed);
277            for ($i = 0; $i < $recentlyUsedCount; $i++) {
278                if ($newQuote == $recentlyUsed[$i]['DayRecord']['quote']) {
279                    $f = true;
280                }
281            }
282            if (!$f) {
283                $quoteChosen = true;
284            }
285        }
286        $currentQuote = $newQuote;
287        $dayUserRand = 1;
288        $uotdChosen = false;
289        while (!$uotdChosen) {
290            $dayUserRand = rand(1, 39);
291            $f = false;
292            $recentlyUsedCount = count($recentlyUsed);
293            for ($i = 0; $i < $recentlyUsedCount; $i++) {
294                if ($dayUserRand == $recentlyUsed[$i]['DayRecord']['userbg']) {
295                    $f = true;
296                }
297            }
298            if (!$f) {
299                $uotdChosen = true;
300            }
301        }
302        $activity = $this->TsumegoAttempt->find('all', ['limit' => 40000, 'conditions' => ['DATE(TsumegoAttempt.created)' => date('Y-m-d', strtotime('yesterday'))]]);
303        if (!$activity) {
304            $activity = [];
305        }
306        $visitedProblems = count($activity);
307
308        //how many users today
309        $usersNum = [];
310        $activity = $this->User->find('all', ['limit' => 400, 'order' => 'created DESC']);
311        if (!$activity) {
312            $activity = [];
313        }
314        $activityCount = count($activity);
315        for ($i = 0; $i < $activityCount; $i++) {
316            $a = new DateTime($activity[$i]['User']['created']);
317            if ($a->format('Y-m-d') == $today) {
318                array_push($usersNum, $activity[$i]['User']);
319            }
320        }
321        $gemRand1 = rand(0, 2);
322        $gemRand2 = rand(0, 2);
323        $gemRand3 = rand(0, 2);
324
325        $arch1 = ClassRegistry::init('Achievement')->findById(111);
326        if ($gemRand1 == 0) {
327            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on an easy ddk problem.';
328        } elseif ($gemRand1 == 1) {
329            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on a regular ddk problem.';
330        } elseif ($gemRand1 == 2) {
331            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult ddk problem.';
332        }
333        ClassRegistry::init('Achievement')->save($arch1);
334        $arch2 = ClassRegistry::init('Achievement')->findById(112);
335        if ($gemRand2 == 0) {
336            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on an easy sdk problem.';
337        } elseif ($gemRand2 == 1) {
338            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on a regular sdk problem.';
339        } elseif ($gemRand2 == 2) {
340            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult sdk problem.';
341        }
342        ClassRegistry::init('Achievement')->save($arch2);
343        $arch3 = ClassRegistry::init('Achievement')->findById(113);
344        if ($gemRand3 == 0) {
345            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on an easy dan problem.';
346        } elseif ($gemRand3 == 1) {
347            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on a regular dan problem.';
348        } elseif ($gemRand3 == 2) {
349            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult dan problem.';
350        }
351        ClassRegistry::init('Achievement')->save($arch3);
352
353        $this->DayRecord->create();
354        $dateUser = [];
355        $dateUser['DayRecord']['user_id'] = $ux['User']['id'];
356        $dateUser['DayRecord']['date'] = $today;
357        $dateUser['DayRecord']['solved'] = $ux['User']['reuse3'];
358        $dateUser['DayRecord']['quote'] = $currentQuote;
359        $dateUser['DayRecord']['userbg'] = $dayUserRand;
360        $dateUser['DayRecord']['tsumego'] = $this->getTsumegoOfTheDay();
361        $dateUser['DayRecord']['newTsumego'] = $this->getNewTsumego();
362        $dateUser['DayRecord']['usercount'] = count($usersNum);
363        $dateUser['DayRecord']['visitedproblems'] = $visitedProblems;
364        $dateUser['DayRecord']['gems'] = $gemRand1 . '-' . $gemRand2 . '-' . $gemRand3;
365        $dateUser['DayRecord']['gemCounter1'] = 0;
366        $dateUser['DayRecord']['gemCounter2'] = 0;
367        $dateUser['DayRecord']['gemCounter3'] = 0;
368        $this->DayRecord->save($dateUser);
369
370        ClassRegistry::init('AchievementCondition')->create();
371        $achievementCondition = [];
372        $achievementCondition['AchievementCondition']['user_id'] = $ux['User']['id'];
373        $achievementCondition['AchievementCondition']['set_id'] = 0;
374        $achievementCondition['AchievementCondition']['category'] = 'uotd';
375        $achievementCondition['AchievementCondition']['value'] = 1;
376        ClassRegistry::init('AchievementCondition')->save($achievementCondition);
377
378        //delete duplicated DayRecords
379        $dr = $this->DayRecord->find('all');
380        if (!$dr) {
381            $dr = [];
382        }
383        $duplicates = [];
384        $drCount = count($dr);
385        for ($i = 0; $i < $drCount; $i++) {
386            $alreadyFound = [];
387            for ($j = 0; $j < $drCount; $j++) {
388                if ($i != $j && $dr[$j]['DayRecord']['date'] == $dr[$i]['DayRecord']['date']) {
389                    $found = false;
390                    $alreadyFoundCount = count($alreadyFound);
391                    for ($k = 0; $k < $alreadyFoundCount; $k++) {
392                        if ($alreadyFound[$k]['DayRecord']['id'] == $dr[$i]['DayRecord']['id'] || $alreadyFound[$k]['DayRecord']['id'] == $dr[$j]['DayRecord']['id']) {
393                            $found = true;
394                        }
395                    }
396                    if (!$found) {
397                        array_push($duplicates, $dr[$i]['DayRecord']['date']);
398                        array_push($alreadyFound, $dr[$i]);
399                    }
400                }
401            }
402        }
403        $duplicates = array_count_values($duplicates);
404        foreach ($duplicates as $key => $value) {
405            while ($duplicates[$key] > 1) {
406                $drd = $this->DayRecord->find('first', ['conditions' => ['date' => $key]]);
407                if ($drd) {
408                    $this->DayRecord->delete($drd['DayRecord']['id']);
409                }
410                $duplicates[$key]--;
411            }
412        }
413    }
414
415    public static function deleteUnusedStatuses(int $uid): void {
416        $s = ClassRegistry::init('Set')->find('all', [
417            'conditions' => [
418                'OR' => [
419                    ['public' => 1],
420                    ['public' => 0],
421                ],
422            ],
423        ]) ?: [];
424        $ids = [];
425        $sCount = count($s);
426        for ($i = 0; $i < $sCount; $i++) {
427            $tSet = TsumegoUtil::collectTsumegosFromSet($s[$i]['Set']['id']);
428            foreach ($tSet as $item) {
429                $ids[] = $item['Tsumego']['id'];
430            }
431        }
432        $ut = ClassRegistry::init('TsumegoStatus')->find('all', [
433            'conditions' => [
434                'user_id' => $uid,
435                'NOT' => [
436                    'tsumego_id' => $ids,
437                ],
438            ],
439        ]);
440        if (!$ut) {
441            $ut = [];
442        }
443        $utCount = count($ut);
444        for ($i = 0; $i < $utCount; $i++) {
445            $test1 = ClassRegistry::init('Tsumego')->findById($ut[$i]['TsumegoStatus']['tsumego_id']);
446            $test2 = ClassRegistry::init('SetConnection')->find('first', ['conditions' => ['tsumego_id' => $test1['Tsumego']['id']]]);
447            if (!$test2) {
448                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
449
450                continue;
451            }
452            $test3 = ClassRegistry::init('Set')->find('first', [
453                'id' => $test2['SetConnection']['set_id'],
454                'OR' => [
455                    ['public' => 1],
456                    ['public' => 0],
457                ],
458            ]);
459            if ($test3 == null) {
460                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
461            }
462        }
463    }
464
465    protected function saveSolvedNumber($uid) {
466        $this->loadModel('User');
467        $this->loadModel('TsumegoStatus');
468        $this->loadModel('Set');
469        $this->loadModel('SetConnection');
470
471        $solvedUts2 = 0;
472        $tsumegos = $this->SetConnection->find('all');
473        if (!$tsumegos) {
474            $tsumegos = [];
475        }
476        $uts = $this->TsumegoStatus->find('all', ['order' => 'created DESC', 'conditions' => ['user_id' => $uid]]);
477        if (!$uts) {
478            $uts = [];
479        }
480        $setKeys = [];
481        $setArray = $this->Set->find('all', ['conditions' => ['public' => 1]]);
482        if (!$setArray) {
483            $setArray = [];
484        }
485
486        $setArrayCount = count($setArray);
487        for ($i = 0; $i < $setArrayCount; $i++) {
488            $setKeys[$setArray[$i]['Set']['id']] = $setArray[$i]['Set']['id'];
489        }
490
491        $scs = [];
492        $tsumegosCount = count($tsumegos);
493        for ($j = 0; $j < $tsumegosCount; $j++) {
494            if (!isset($scs[$tsumegos[$j]['SetConnection']['tsumego_id']])) {
495                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']] = 1;
496            } else {
497                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']]++;
498            }
499        }
500        $utsCount = count($uts);
501        for ($j = 0; $j < $utsCount; $j++) {
502            if ($uts[$j]['TsumegoStatus']['status'] == 'S' || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C') {
503                if (isset($scs[$uts[$j]['TsumegoStatus']['tsumego_id']])) {
504                    $solvedUts2 += $scs[$uts[$j]['TsumegoStatus']['tsumego_id']];
505                }
506            }
507        }
508        Auth::getUser()['solved'] = $solvedUts2;
509        Auth::saveUser();
510
511        return $solvedUts2;
512    }
513
514    public static function convertEloToXp($elo) {
515        $xp = round(pow($elo / 100, 1.55) - 6);
516        if ($xp < 10) {
517            $xp = 10;
518        }
519
520        return $xp;
521    }
522
523    /**
524     * @return void
525     */
526    protected function resetUserElos() {
527        $this->loadModel('User');
528
529        $u = $this->User->find('all', [
530            'conditions' => [
531                'id >=' => 15000,
532                'id <=' => 19000,
533            ],
534        ]);
535        if (!$u) {
536            $u = [];
537        }
538
539        $uCount = count($u);
540        for ($i = 0; $i < $uCount; $i++) {
541            $u[$i]['User']['rating'] = 900;
542            $u[$i]['User']['solved2'] = 0;
543            $this->User->save($u[$i]);
544        }
545    }
546
547    public static function getNewElo($diff, $eloBigger, $activityValue, $tid, $outcome) {
548        $return = [];
549        $t = ClassRegistry::init('Tsumego')->findById($tid);
550        if ($t['Tsumego']['activity_value'] > 300) {
551            $t['Tsumego']['activity_value'] = 300;
552        }
553        $tsumegoAvtivityValue = max(round((2 / 3) * $t['Tsumego']['activity_value']), 15);
554        $kFactor1 = 1;
555        $kFactor2 = 1;
556        if (Auth::isLoggedIn()) {
557            $rating = Auth::getUser()['rating'];
558            if ($rating >= 1500) {
559                $kFactor1 = 1.5;
560                $kFactor2 = 0.9;
561            } elseif ($rating >= 1800) {
562                $kFactor1 = 2;
563                $kFactor2 = 0.8;
564            } elseif ($rating >= 2100) {
565                $kFactor1 = 2.5;
566                $kFactor2 = 0.7;
567            } elseif ($rating >= 2400) {
568                $kFactor1 = 3;
569                $kFactor2 = 0.6;
570            }
571        }
572        if ($diff == 0) {
573            $diff = .1;
574        }
575        $tWin = 0;
576        $tLoss = 0;
577        $uWin = 0;
578        $uLoss = 0;
579        if ($eloBigger == 'u') {
580            $tWin = $diff / $tsumegoAvtivityValue;
581            $tLoss = 0;
582
583            $uWin = log($diff, 2) - $diff / 70;
584            if ($diff <= 100) {
585                $uWin = 5;
586            }
587            $uWin *= $kFactor2;
588            if ($uWin < 1) {
589                $uWin = 1 - $diff / 1400;
590            }
591            if ($uWin > 5) {
592                $uWin = 5;
593            }
594
595            $uLoss = log($diff, 2) * 2.2 - 12;
596            $uLoss *= $kFactor2;
597            if ($uLoss < 5) {
598                $uLoss = 5;
599            }
600            $uLoss *= -1;
601
602            if ($diff > 1000) {
603                $uWin = 0;
604                $uLoss = 0;
605            }
606        } elseif ($eloBigger == 't') {
607            $tWin = 0;
608            $tLoss = $diff / $tsumegoAvtivityValue * (-1);
609
610            $uWin = log($diff, 2) * 2.2 - 11;
611            $uWin *= $kFactor2;
612            if ($uWin < 5) {
613                $uWin = 5;
614            }
615
616            $uLoss = log($diff, 2) - $diff / 70 - 1;
617            if ($diff < 100) {
618                $uLoss = 4;
619            }
620            $uLoss *= $kFactor2;
621            if ($uLoss < 1) {
622                $uLoss = 1 - $diff / 1400;
623            }
624            $uLoss *= -1;
625        }
626
627        $activityValueBase = 1;
628        if ($activityValue < 30) {
629            $activityValueAdd = 0;
630        } elseif ($activityValue < 50) {
631            $activityValueAdd = 0.6;
632        } elseif ($activityValue < 70) {
633            $activityValueAdd = 1.2;
634        } else {
635            $activityValueAdd = 1.8;
636        }
637
638        $activityValueSum = $activityValueBase + ($activityValueAdd / $kFactor1);
639
640        if ($outcome == 'w') {
641            $return['user'] = round($uWin * $activityValueSum, 2);
642            $return['user2'] = $uWin * $activityValueSum;
643            $return['tsumego'] = round($tLoss);
644            $return['tsumego2'] = $tLoss;
645        } else {
646            $return['user'] = round($uLoss * $activityValueSum, 2);
647            $return['user2'] = $uLoss * $activityValueSum;
648            $return['tsumego'] = round($tWin);
649            $return['tsumego2'] = $tWin;
650        }
651
652        return $return;
653    }
654
655    /**
656     * @param int $uid User ID
657     * @param string $action Action type
658     *
659     * @return void
660     */
661    public static function handleContribution($uid, $action) {
662        $uc = ClassRegistry::init('UserContribution')->find('first', ['conditions' => ['user_id' => $uid]]);
663        if ($uc == null) {
664            $uc = [];
665            $uc['UserContribution']['user_id'] = $uid;
666            $uc['UserContribution']['added_tag'] = 0;
667            $uc['UserContribution']['created_tag'] = 0;
668            $uc['UserContribution']['made_proposal'] = 0;
669            $uc['UserContribution']['reviewed'] = 0;
670            $uc['UserContribution']['score'] = 0;
671            ClassRegistry::init('UserContribution')->create();
672        }
673        $uc['UserContribution'][$action] += 1;
674        $uc['UserContribution']['score']
675        = $uc['UserContribution']['added_tag']
676        + $uc['UserContribution']['created_tag'] * 3
677        + $uc['UserContribution']['made_proposal'] * 5
678        + $uc['UserContribution']['reviewed'] * 2;
679        ClassRegistry::init('UserContribution')->save($uc);
680    }
681
682    public static function getAllTags($not) {
683        $a = [];
684        $notApproved = ClassRegistry::init('TagName')->find('all', ['conditions' => ['approved' => 0]]);
685        if (!$notApproved) {
686            $notApproved = [];
687        }
688        $notCount = count($not);
689        for ($i = 0; $i < $notCount; $i++) {
690            array_push($a, $not[$i]['Tag']['tag_name_id']);
691        }
692        $notApprovedCount = count($notApproved);
693        for ($i = 0; $i < $notApprovedCount; $i++) {
694            array_push($a, $notApproved[$i]['TagName']['id']);
695        }
696        $tn = ClassRegistry::init('TagName')->find('all', [
697            'conditions' => [
698                'NOT' => ['id' => $a],
699            ],
700        ]);
701        if (!$tn) {
702            $tn = [];
703        }
704        $sorted = [];
705        $keys = [];
706        $tnCount = count($tn);
707        for ($i = 0; $i < $tnCount; $i++) {
708            array_push($sorted, $tn[$i]['TagName']['name']);
709            $keys[$tn[$i]['TagName']['name']] = $tn[$i];
710        }
711        sort($sorted);
712        $s2 = [];
713        $sortedCount = count($sorted);
714        for ($i = 0; $i < $sortedCount; $i++) {
715            array_push($s2, $keys[$sorted[$i]]);
716        }
717
718        return $s2;
719    }
720
721    /**
722     * @param int|null $range Range parameter
723     *
724     * @return void
725     */
726    protected function userRefresh($range = null) {
727        $this->loadModel('User');
728        $this->loadModel('TsumegoStatus');
729        $u = [];
730        if ($range == 1) {
731            $u = $this->User->find('all', [
732                'order' => 'id DESC',
733                'conditions' => [
734                    'id <' => 2000,
735                ],
736            ]);
737            if (!$u) {
738                $u = [];
739            }
740        } elseif ($range == 2) {
741            $u = $this->User->find('all', [
742                'order' => 'id DESC',
743                'conditions' => [
744                    'id >=' => 2000,
745                    'id <' => 4000,
746                ],
747            ]);
748            if (!$u) {
749                $u = [];
750            }
751        } elseif ($range == 3) {
752            $u = $this->User->find('all', [
753                'order' => 'id DESC',
754                'conditions' => [
755                    'id >=' => 4000,
756                    'id <' => 6000,
757                ],
758            ]);
759            if (!$u) {
760                $u = [];
761            }
762        } elseif ($range == 4) {
763            $u = $this->User->find('all', [
764                'order' => 'id DESC',
765                'conditions' => [
766                    'id >=' => 6000,
767                    'id <' => 8000,
768                ],
769            ]);
770            if (!$u) {
771                $u = [];
772            }
773        } elseif ($range == 5) {
774            $u = $this->User->find('all', [
775                'order' => 'id DESC',
776                'conditions' => [
777                    'id >=' => 8000,
778                    'id <' => 10000,
779                ],
780            ]);
781            if (!$u) {
782                $u = [];
783            }
784        } elseif ($range == 6) {
785            $u = $this->User->find('all', [
786                'order' => 'id DESC',
787                'conditions' => [
788                    'id >=' => 10000,
789                    'id <' => 12000,
790                ],
791            ]);
792            if (!$u) {
793                $u = [];
794            }
795        } elseif ($range == 7) {
796            $u = $this->User->find('all', [
797                'order' => 'id DESC',
798                'conditions' => [
799                    'id >=' => 12000,
800                    'id <' => 14000,
801                ],
802            ]);
803            if (!$u) {
804                $u = [];
805            }
806        } elseif ($range == 8) {
807            $u = $this->User->find('all', [
808                'order' => 'id DESC',
809                'conditions' => [
810                    'id >=' => 14000,
811                    'id <' => 16000,
812                ],
813            ]);
814            if (!$u) {
815                $u = [];
816            }
817        } elseif ($range == 9) {
818            $u = $this->User->find('all', [
819                'order' => 'id DESC',
820                'conditions' => [
821                    'id >=' => 16000,
822                    'id <' => 18000,
823                ],
824            ]);
825            if (!$u) {
826                $u = [];
827            }
828        } elseif ($range == 10) {
829            $u = $this->User->find('all', [
830                'order' => 'id DESC',
831                'conditions' => [
832                    'id >=' => 18000,
833                    'id <' => 20000,
834                ],
835            ]);
836            if (!$u) {
837                $u = [];
838            }
839        } elseif ($range == 11) {
840            $u = $this->User->find('all', [
841                'order' => 'id DESC',
842                'conditions' => [
843                    'id >=' => 20000,
844                    'id <' => 22000,
845                ],
846            ]);
847            if (!$u) {
848                $u = [];
849            }
850        } elseif ($range == 12) {
851            $u = $this->User->find('all', [
852                'order' => 'id DESC',
853                'conditions' => [
854                    'id >=' => 22000,
855                ],
856            ]);
857            if (!$u) {
858                $u = [];
859            }
860        }
861        $uCount = count($u);
862        for ($i = 0; $i < $uCount; $i++) {
863            $this->User->create();
864            $u[$i]['User']['reuse2'] = 0;//#
865            $u[$i]['User']['reuse3'] = 0;//xp
866            $u[$i]['User']['reuse4'] = 0;//daily maximum
867            $u[$i]['User']['damage'] = 0;
868            $u[$i]['User']['sprint'] = 1;
869            $u[$i]['User']['intuition'] = 1;
870            $u[$i]['User']['rejuvenation'] = 1;
871            $u[$i]['User']['refinement'] = 1;
872            $u[$i]['User']['revelation'] = 5;
873            $u[$i]['User']['usedSprint'] = 0;
874            $u[$i]['User']['usedRejuvenation'] = 0;
875            $u[$i]['User']['usedRefinement'] = 0;
876            $u[$i]['User']['readingTrial'] = 30;
877            $u[$i]['User']['potion'] = 0;
878            $u[$i]['User']['promoted'] += 1;
879            $u[$i]['User']['lastRefresh'] = date('Y-m-d');
880            if ($u[$i]['User']['isAdmin'] > 0) {
881                $u[$i]['User']['revelation'] = 20;
882            }
883            $this->User->save($u[$i]);
884        }
885        $uts = $this->TsumegoStatus->find('all', ['conditions' => ['status' => 'F']]);
886        if (!$uts) {
887            $uts = [];
888        }
889        $utsCount = count($uts);
890        for ($i = 0; $i < $utsCount; $i++) {
891            $uts[$i]['TsumegoStatus']['status'] = 'V';
892            //$this->TsumegoStatus->save($uts[$i]);
893        }
894        $uts = $this->TsumegoStatus->find('all', ['conditions' => ['status' => 'X']]);
895        if (!$uts) {
896            $uts = [];
897        }
898        $utsCount = count($uts);
899        for ($i = 0; $i < $utsCount; $i++) {
900            $uts[$i]['TsumegoStatus']['status'] = 'W';
901            //$this->TsumegoStatus->save($uts[$i]);
902        }
903    }
904
905    /**
906     * @return void
907     */
908    protected function deleteUserBoards() {
909        $this->loadModel('UserBoard');
910        $this->UserBoard->deleteAll(['1 = 1']);
911    }
912
913    /**
914     * @return void
915     */
916    protected function halfXP() {
917        $this->loadModel('TsumegoStatus');
918        $this->loadModel('DayRecord');
919        $week = $this->TsumegoStatus->find('all', ['order' => 'created DESC', 'conditions' => ['status' => 'S']]);
920        if (!$week) {
921            $week = [];
922        }
923        $oneWeek = date('Y-m-d H:i:s', strtotime('-7 days'));
924        $weekCount = count($week);
925        for ($i = 0; $i < $weekCount; $i++) {
926            if ($week[$i]['TsumegoStatus']['created'] < $oneWeek) {
927                if ($week[$i]['TsumegoStatus']['status'] == 'S') {
928                    $week[$i]['TsumegoStatus']['status'] = 'W';
929                    //$this->TsumegoStatus->save($week[$i]);
930                }
931            }
932        }
933    }
934
935    protected function getNewTsumego() {
936        $this->loadModel('Schedule');
937        $date = date('Y-m-d', strtotime('today'));
938        $s = $this->Schedule->find('all', ['conditions' => ['date' => $date]]);
939        if (!$s) {
940            $s = [];
941        }
942        $id = 0;
943        $sCount = count($s);
944        for ($i = 0; $i < $sCount; $i++) {
945            $id = $this->publishSingle($s[$i]['Schedule']['tsumego_id'], $s[$i]['Schedule']['set_id'], $s[$i]['Schedule']['date']);
946            $s[$i]['Schedule']['tsumego_id'] = $id;
947            $s[$i]['Schedule']['published'] = 1;
948            $this->Schedule->save($s[$i]);
949        }
950
951        return $id;
952    }
953
954    protected function publishSingle($t = null, $to = null, $date = null) {
955        $this->loadModel('Tsumego');
956        $this->loadModel('Sgf');
957        $this->loadModel('SetConnection');
958        $this->loadModel('PublishDate');
959        $ts = $this->Tsumego->findById($t);
960
961        $id = $this->Tsumego->find('first', ['limit' => 1, 'order' => 'id DESC']);
962        if (!$id) {
963            return null;
964        }
965        $id = $id['Tsumego']['id'];
966        $id += 1;
967
968        $scT = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $ts['Tsumego']['id']]]);
969        if ($scT != null) {
970            $scT['SetConnection']['set_id'] = $to;
971            $scT['SetConnection']['tsumego_id'] = $id;
972            $scT['SetConnection']['num'] = $ts['Tsumego']['num'];
973            $this->SetConnection->save($scT);
974        } else {
975            $scT = [];
976            $scT['SetConnection']['set_id'] = $to;
977            $scT['SetConnection']['tsumego_id'] = $id;
978            $scT['SetConnection']['num'] = $ts['Tsumego']['num'];
979            $this->SetConnection->create();
980            $this->SetConnection->save($scT);
981        }
982
983        $sid = $ts['Tsumego']['id'];
984        $ts['Tsumego']['id'] = $id;
985        $ts['Tsumego']['created'] = $date . ' 22:00:00';
986        $ts['Tsumego']['solved'] = 0;
987        $ts['Tsumego']['failed'] = 0;
988        $ts['Tsumego']['userWin'] = 0;
989        $ts['Tsumego']['userLoss'] = 0;
990        $this->Tsumego->create();
991        $this->Tsumego->save($ts);
992        $this->Tsumego->delete($sid);
993
994        $sgfs = $this->Sgf->find('all', ['conditions' => ['tsumego_id' => $t]]);
995        if (!$sgfs) {
996            $sgfs = [];
997        }
998        $sgfsCount = count($sgfs);
999        for ($i = 0; $i < $sgfsCount; $i++) {
1000            $sgfs[$i]['Sgf']['tsumego_id'] = $id;
1001            $this->Sgf->save($sgfs[$i]);
1002        }
1003        $x = [];
1004        $x['PublishDate']['date'] = $date . ' 22:00:00';
1005        $x['PublishDate']['tsumego_id'] = $id;
1006        $this->PublishDate->create();
1007        $this->PublishDate->save($x);
1008
1009        return $id;
1010    }
1011
1012    protected function getTsumegoOfTheDay() {
1013        $this->loadModel('TsumegoAttempt');
1014        $this->loadModel('TsumegoRatingAttempt');
1015        $this->loadModel('Schedule');
1016        $this->loadModel('Tsumego');
1017        $this->loadModel('SetConnection');
1018
1019        $ut = $this->TsumegoRatingAttempt->find('all', ['limit' => 10000, 'order' => 'created DESC', 'conditions' => ['status' => 'S']]);
1020        if (!$ut) {
1021            $ut = [];
1022        }
1023        $out = $this->TsumegoAttempt->find('all', ['limit' => 30000, 'order' => 'created DESC', 'conditions' => ['gain >=' => 40]]);
1024        if (!$out) {
1025            $out = [];
1026        }
1027
1028        $date = date('Y-m-d', strtotime('yesterday'));
1029        $s = $this->Schedule->find('all', ['conditions' => ['date' => $date]]);
1030        if (!$s) {
1031            $s = [];
1032        }
1033        $ids = [];
1034        $utCount = count($ut);
1035        for ($i = 0; $i < $utCount; $i++) {
1036            $date2 = new DateTime($ut[$i]['TsumegoRatingAttempt']['created']);
1037            $date2 = $date2->format('Y-m-d');
1038            if ($date === $date2) {
1039                array_push($ids, $ut[$i]['TsumegoRatingAttempt']['tsumego_id']);
1040            }
1041        }
1042        $ids = array_count_values($ids);
1043        $highest = 0;
1044        $best = [];
1045        foreach ($ids as $key => $value) {
1046            if ($value > $highest) {
1047                $highest = $value;
1048            }
1049        }
1050        foreach ($ids as $key => $value) {
1051            if ($value == $highest) {
1052                $x = [];
1053                $x[$key] = $value;
1054                array_push($best, $x);
1055            }
1056        }
1057        $ids2 = [];
1058        $out2 = [];
1059        $outCount = count($out);
1060        for ($i = 0; $i < $outCount; $i++) {
1061            $date2 = new DateTime($out[$i]['TsumegoAttempt']['created']);
1062            $date2 = $date2->format('Y-m-d');
1063            if ($date === $date2) {
1064                array_push($ids2, $out[$i]['TsumegoAttempt']['tsumego_id']);
1065                array_push($out2, $out[$i]);
1066            }
1067        }
1068        $ids2 = array_count_values($ids2);
1069        $highest = 0;
1070        $best2 = [];
1071        foreach ($ids2 as $key => $value) {
1072            if ($value > $highest) {
1073                $highest = $value;
1074            }
1075        }
1076        $done = false;
1077        $found = 0;
1078        $decrement = 0;
1079        $best3 = [];
1080        $findNum = 20;
1081        while (!$done) {
1082            foreach ($ids2 as $key => $value) {
1083                if ($value == $highest - $decrement) {
1084                    array_push($best2, $key);
1085                    array_push($best3, $value);
1086                    $found++;
1087                }
1088            }
1089            $decrement++;
1090            if ($found < $findNum) {
1091                $done = false;
1092            } else {
1093                $done = true;
1094            }
1095        }
1096        $newBest = [];
1097        for ($j = 0; $j < $findNum; $j++) {
1098            $newBest[$j] = [];
1099        }
1100        $out2Count = count($out2);
1101        for ($i = 0; $i < $out2Count; $i++) {
1102            for ($j = 0; $j < $findNum; $j++) {
1103                if ($out2[$i]['TsumegoAttempt']['tsumego_id'] == $best2[$j]) {
1104                    $x = [];
1105                    $x['tid'] = $out2[$i]['TsumegoAttempt']['tsumego_id'];
1106                    $tx = $this->Tsumego->findById($x['tid']);
1107                    $scT = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $tx['Tsumego']['id']]]);
1108                    $tx['Tsumego']['set_id'] = $scT['SetConnection']['set_id'];
1109                    $x['sid'] = $tx['Tsumego']['set_id'];
1110                    $x['status'] = $out2[$i]['TsumegoAttempt']['solved'];
1111                    $x['seconds'] = $out2[$i]['TsumegoAttempt']['seconds'];
1112
1113                    $newBest[$j][] = $x;
1114                }
1115            }
1116        }
1117        $newBestCount = count($newBest);
1118        for ($i = 0; $i < $newBestCount; $i++) {
1119            $sum = 0;
1120            $newBestICount = count($newBest[$i]);
1121            for ($j = 0; $j < $newBestICount; $j++) {
1122                if ($newBest[$i][$j]['seconds'] != null) {
1123                    if ($newBest[$i][$j]['seconds'] > 300) {
1124                        $newBest[$i][$j]['seconds'] = 300;
1125                    }
1126                    $sum += $newBest[$i][$j]['seconds'];
1127                }
1128            }
1129            $sum = $sum * count($newBest[$i]);
1130            $newBest[$i]['sum'] = $sum;
1131        }
1132        $highest = 0;
1133        $hid = 0;
1134        $newBestCount = count($newBest);
1135        for ($i = 0; $i < $newBestCount; $i++) {
1136            if ($newBest[$i]['sum'] > $highest && $newBest[$i][0]['sid'] != 104 && $newBest[$i][0]['sid'] != 105 && $newBest[$i][0]['sid'] != 117) {
1137                $yesterday = false;
1138                $sCount = count($s);
1139                for ($j = 0; $j < $sCount; $j++) {
1140                    if ($newBest[$i][0]['tid'] == $s[$j]['Schedule']['tsumego_id']) {
1141                        $yesterday = true;
1142                    }
1143                }
1144                if (!$yesterday) {
1145                    $highest = $newBest[$i]['sum'];
1146                    $hid = $i;
1147                }
1148            }
1149        }
1150
1151        return $newBest[$hid][0]['tid'];
1152    }
1153
1154    protected function ratingMatch($elo) {
1155        if ($elo >= 3000) {
1156            $td = 10;//10d
1157        } elseif ($elo >= 2900) {
1158            $td = 10;//9d
1159        } elseif ($elo >= 2800) {
1160            $td = 10;//8d
1161        } elseif ($elo >= 2700) {
1162            $td = 10;//7d x2700
1163        } elseif ($elo >= 2600) {
1164            $td = 9;//6d x2600
1165        } elseif ($elo >= 2500) {
1166            $td = 8;//5d x2500
1167        } elseif ($elo >= 2400) {
1168            $td = 7;//4d
1169        } elseif ($elo >= 2300) {
1170            $td = 7;//3d x2350
1171        } elseif ($elo >= 2200) {
1172            $td = 6;//2d
1173        } elseif ($elo >= 2100) {
1174            $td = 6;//1d x2150
1175        } elseif ($elo >= 2000) {
1176            $td = 5;//1k
1177        } elseif ($elo >= 1900) {
1178            $td = 5;//2k x1950
1179        } elseif ($elo >= 1800) {
1180            $td = 4;//3k
1181        } elseif ($elo >= 1700) {
1182            $td = 4;//4k x1750
1183        } elseif ($elo >= 1600) {
1184            $td = 3;//5k
1185        } elseif ($elo >= 1500) {
1186            $td = 3;//6k x1500
1187        } elseif ($elo >= 1400) {
1188            $td = 3;//7k
1189        } elseif ($elo >= 1300) {
1190            $td = 2;//8k
1191        } elseif ($elo >= 1200) {
1192            $td = 2;//9k x1200
1193        } elseif ($elo >= 1100) {
1194            $td = 2;//10k
1195        } elseif ($elo >= 1000) {
1196            $td = 1;//11k
1197        } elseif ($elo >= 900) {
1198            $td = 1;//12k x900
1199        } elseif ($elo >= 800) {
1200            $td = 1;//13k
1201        } elseif ($elo >= 700) {
1202            $td = 1;//14k
1203        } elseif ($elo >= 600) {
1204            $td = 1;//15k
1205        } elseif ($elo >= 500) {
1206            $td = 1;//16k
1207        } elseif ($elo >= 400) {
1208            $td = 1;//17k
1209        } elseif ($elo >= 300) {
1210            $td = 1;//18k
1211        } elseif ($elo >= 200) {
1212            $td = 1;//19k
1213        } elseif ($elo >= 100) {
1214            $td = 1;//20k
1215        } else {
1216            $td = 1;
1217        }
1218
1219        return $td;
1220    }
1221
1222    protected function rating2($d) {
1223        if ($d == 10) {
1224            $elo = 2700;
1225        } elseif ($d == 9) {
1226            $elo = 2600;
1227        } elseif ($d == 8) {
1228            $elo = 2500;
1229        } elseif ($d == 7) {
1230            $elo = 2350;
1231        } elseif ($d == 6) {
1232            $elo = 2150;
1233        } elseif ($d == 5) {
1234            $elo = 1950;
1235        } elseif ($d == 4) {
1236            $elo = 1750;
1237        } elseif ($d == 3) {
1238            $elo = 1500;
1239        } elseif ($d == 2) {
1240            $elo = 1200;
1241        } elseif ($d == 1) {
1242            $elo = 900;
1243        } else {
1244            $elo = 1500;
1245        }
1246
1247        return $elo;
1248    }
1249
1250    public static function encrypt($str = null) {
1251        $secret_key = 'my_simple_secret_keyx';
1252        $secret_iv = 'my_simple_secret_ivx';
1253        $encrypt_method = 'AES-256-CBC';
1254        $key = hash('sha256', $secret_key);
1255        $iv = substr(hash('sha256', $secret_iv), 0, 16);
1256
1257        return base64_encode(openssl_encrypt($str, $encrypt_method, $key, 0, $iv));
1258    }
1259
1260    public static function decrypt($str = null) {
1261        $string = $str;
1262        $secret_key = 'my_simple_secret_keyx';
1263        $secret_iv = 'my_simple_secret_ivx';
1264        $encrypt_method = 'AES-256-CBC';
1265        $key = hash('sha256', $secret_key);
1266        $iv = substr(hash('sha256', $secret_iv), 0, 16);
1267
1268        return openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
1269    }
1270
1271    protected function checkPictureLarge($u) {
1272        if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
1273            return '<img class="google-profile-image-large" src="/img/google/' . $u['User']['picture'] . '">' . substr($u['User']['name'], 3);
1274        }
1275
1276        return $u['User']['name'];
1277    }
1278    public static function checkPicture($user) {
1279        if (substr($user['name'], 0, 3) == 'g__' && $user['external_id'] != null) {
1280            return '<img class="google-profile-image" src="/img/google/' . $user['picture'] . '">' . substr($user['name'], 3);
1281        }
1282
1283        return $user['name'];
1284    }
1285
1286    public static function getTsumegoRankx($t) {
1287        if ($t <= 0) {
1288            return '15k';
1289        }
1290        if ($t > 0 && $t <= 22) {
1291            $tRank = '5d';
1292        } elseif ($t <= 26.5) {
1293            $tRank = '4d';
1294        } elseif ($t <= 30) {
1295            $tRank = '3d';
1296        } elseif ($t <= 34) {
1297            $tRank = '2d';
1298        } elseif ($t <= 38) {
1299            $tRank = '1d';
1300        } elseif ($t <= 42) {
1301            $tRank = '1k';
1302        } elseif ($t <= 46) {
1303            $tRank = '2k';
1304        } elseif ($t <= 50) {
1305            $tRank = '3k';
1306        } elseif ($t <= 54.5) {
1307            $tRank = '4k';
1308        } elseif ($t <= 58.5) {
1309            $tRank = '5k';
1310        } elseif ($t <= 63) {
1311            $tRank = '6k';
1312        } elseif ($t <= 67) {
1313            $tRank = '7k';
1314        } elseif ($t <= 70.8) {
1315            $tRank = '8k';
1316        } elseif ($t <= 74.8) {
1317            $tRank = '9k';
1318        } elseif ($t <= 79) {
1319            $tRank = '10k';
1320        } elseif ($t <= 83.5) {
1321            $tRank = '11k';
1322        } elseif ($t <= 88) {
1323            $tRank = '12k';
1324        } elseif ($t <= 92) {
1325            $tRank = '13k';
1326        } elseif ($t <= 96) {
1327            $tRank = '14k';
1328        } else {
1329            $tRank = '15k';
1330        }
1331
1332        return $tRank;
1333    }
1334    protected function adjustElo($v) {
1335        $add = 0;
1336        if ($v >= 1700) {
1337            $add = 110;
1338        } elseif ($v >= 1600) {
1339            $add = 110;
1340        } elseif ($v >= 1700) {
1341            $add = 100;
1342        } elseif ($v >= 1600) {
1343            $add = 90;
1344        } elseif ($v >= 1500) {
1345            $add = 80;
1346        } elseif ($v >= 1400) {
1347            $add = 70;
1348        } elseif ($v >= 1300) {
1349            $add = 60;
1350        } elseif ($v >= 1200) {
1351            $add = 60;
1352        } elseif ($v >= 1100) {
1353            $add = 50;
1354        } elseif ($v >= 1000) {
1355            $add = 50;
1356        } else {
1357            $add = 0;
1358        }
1359
1360        return $v + $add;
1361    }
1362
1363    public static function getTsumegoElo($rank, $p = null) {
1364        if ($p != null) {
1365            $p *= 100;
1366        } else {
1367            $p = 0;
1368        }
1369        $elo = 600;
1370        if ($rank == '9d') {
1371            $elo = round(2900 + $p);
1372        } elseif ($rank == '8d') {
1373            $elo = round(2800 + $p);
1374        } elseif ($rank == '7d') {
1375            $elo = round(2700 + $p);
1376        } elseif ($rank == '6d') {
1377            $elo = round(2600 + $p);
1378        } elseif ($rank == '5d') {
1379            $elo = round(2500 + $p);
1380        } elseif ($rank == '4d') {
1381            $elo = round(2400 + $p);
1382        } elseif ($rank == '3d') {
1383            $elo = round(2300 + $p);
1384        } elseif ($rank == '2d') {
1385            $elo = round(2200 + $p);
1386        } elseif ($rank == '1d') {
1387            $elo = round(2100 + $p);
1388        } elseif ($rank == '1k') {
1389            $elo = round(2000 + $p);
1390        } elseif ($rank == '2k') {
1391            $elo = round(1900 + $p);
1392        } elseif ($rank == '3k') {
1393            $elo = round(1800 + $p);
1394        } elseif ($rank == '4k') {
1395            $elo = round(1700 + $p);
1396        } elseif ($rank == '5k') {
1397            $elo = round(1600 + $p);
1398        } elseif ($rank == '6k') {
1399            $elo = round(1500 + $p);
1400        } elseif ($rank == '7k') {
1401            $elo = round(1400 + $p);
1402        } elseif ($rank == '8k') {
1403            $elo = round(1300 + $p);
1404        } elseif ($rank == '9k') {
1405            $elo = round(1200 + $p);
1406        } elseif ($rank == '10k') {
1407            $elo = round(1100 + $p);
1408        } elseif ($rank == '11k') {
1409            $elo = round(1000 + $p);
1410        } elseif ($rank == '12k') {
1411            $elo = round(900 + $p);
1412        } elseif ($rank == '13k') {
1413            $elo = round(800 + $p);
1414        } elseif ($rank == '14k') {
1415            $elo = round(700 + $p);
1416        } elseif ($rank == '15k' || $rank == '16k' || $rank == '17k' || $rank == '18k' || $rank == '19k' || $rank == '20k' || $rank == '21k') {
1417            $elo = round(600 + $p);
1418        }
1419
1420        return $elo;
1421    }
1422    protected function getTsumegoRankVal($t) {
1423        if ($t <= 0) {
1424            return 0;
1425        }
1426        if ($t > 0 && $t <= 22) {
1427            return 22 - $t;
1428        }
1429        if ($t <= 26.5) {
1430            return 26.5 - $t;
1431        }
1432        if ($t <= 30) {
1433            return 30 - $t;
1434        }
1435        if ($t <= 34) {
1436            return 34 - $t;
1437        }
1438        if ($t <= 38) {
1439            return 38 - $t;
1440        }
1441        if ($t <= 42) {
1442            return 42 - $t;
1443        }
1444        if ($t <= 46) {
1445            return 46 - $t;
1446        }
1447        if ($t <= 50) {
1448            return 50 - $t;
1449        }
1450        if ($t <= 54.5) {
1451            return 54.5 - $t;
1452        }
1453        if ($t <= 58.5) {
1454            return 58.5 - $t;
1455        }
1456        if ($t <= 63) {
1457            return 63 - $t;
1458        }
1459        if ($t <= 67) {
1460            return 67 - $t;
1461        }
1462        if ($t <= 70.8) {
1463            return 70.8 - $t;
1464        }
1465        if ($t <= 74.8) {
1466            return 74.8 - $t;
1467        }
1468        if ($t <= 79) {
1469            return 79 - $t;
1470        }
1471        if ($t <= 83.5) {
1472            return 83.5 - $t;
1473        }
1474        if ($t <= 88) {
1475            return 88 - $t;
1476        }
1477        if ($t <= 92) {
1478            return 92 - $t;
1479        }
1480        if ($t <= 96) {
1481            return 96 - $t;
1482        }
1483
1484        return 100 - $t;
1485    }
1486    protected function getTsumegoRankMax($t) {
1487        if ($t <= 0) {
1488            return 100 - 96;
1489        }
1490        if ($t > 0 && $t <= 22) {
1491            return 22;
1492        }
1493        if ($t <= 26.5) {
1494            return 26.5 - 22;
1495        }
1496        if ($t <= 30) {
1497            return 30 - 26.5;
1498        }
1499        if ($t <= 34) {
1500            return 34 - 30;
1501        }
1502        if ($t <= 38) {
1503            return 38 - 34;
1504        }
1505        if ($t <= 42) {
1506            return 42 - 38;
1507        }
1508        if ($t <= 46) {
1509            return 46 - 42;
1510        }
1511        if ($t <= 50) {
1512            return 50 - 46;
1513        }
1514        if ($t <= 54.5) {
1515            return 54.5 - 50;
1516        }
1517        if ($t <= 58.5) {
1518            return 58.5 - 54.5;
1519        }
1520        if ($t <= 63) {
1521            return 63 - 58.5;
1522        }
1523        if ($t <= 67) {
1524            return 67 - 63;
1525        }
1526        if ($t <= 70.8) {
1527            return 70.8 - 67;
1528        }
1529        if ($t <= 74.8) {
1530            return 74.8 - 70.8;
1531        }
1532        if ($t <= 79) {
1533            return 79 - 74.8;
1534        }
1535        if ($t <= 83.5) {
1536            return 83.5 - 79;
1537        }
1538        if ($t <= 88) {
1539            return 88 - 83.5;
1540        }
1541        if ($t <= 92) {
1542            return 92 - 88;
1543        }
1544        if ($t <= 96) {
1545            return 96 - 92;
1546        }
1547
1548        return 100 - 96;
1549    }
1550
1551    public static function saveDanSolveCondition($solvedTsumegoRank, $tId): void {
1552        if ($solvedTsumegoRank == '1d' || $solvedTsumegoRank == '2d' || $solvedTsumegoRank == '3d' || $solvedTsumegoRank == '4d' || $solvedTsumegoRank == '5d') {
1553            $danSolveCategory = 'danSolve' . $solvedTsumegoRank;
1554            $danSolveCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1555                'order' => 'value DESC',
1556                'conditions' => [
1557                    'user_id' => Auth::getUserID(),
1558                    'category' => $danSolveCategory,
1559                ],
1560            ]);
1561            if (!$danSolveCondition) {
1562                $danSolveCondition = [];
1563                $danSolveCondition['AchievementCondition']['value'] = 0;
1564                ClassRegistry::init('AchievementCondition')->create();
1565            }
1566            $danSolveCondition['AchievementCondition']['category'] = $danSolveCategory;
1567            $danSolveCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1568            $danSolveCondition['AchievementCondition']['set_id'] = $tId;
1569            $danSolveCondition['AchievementCondition']['value']++;
1570
1571            ClassRegistry::init('AchievementCondition')->save($danSolveCondition);
1572        }
1573    }
1574
1575    public static function updateSprintCondition(bool $trigger = false): void {
1576        if (Auth::isLoggedIn()) {
1577            $sprintCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1578                'order' => 'value DESC',
1579                'conditions' => [
1580                    'user_id' => Auth::getUserID(),
1581                    'category' => 'sprint',
1582                ],
1583            ]);
1584            if (!$sprintCondition) {
1585                $sprintCondition = [];
1586                $sprintCondition['AchievementCondition']['value'] = 0;
1587                ClassRegistry::init('AchievementCondition')->create();
1588            }
1589            $sprintCondition['AchievementCondition']['category'] = 'sprint';
1590            $sprintCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1591            if ($trigger) {
1592                $sprintCondition['AchievementCondition']['value']++;
1593            } else {
1594                $sprintCondition['AchievementCondition']['value'] = 0;
1595            }
1596            ClassRegistry::init('AchievementCondition')->save($sprintCondition);
1597        }
1598    }
1599
1600    public static function updateGoldenCondition(bool $trigger = false): void {
1601        $goldenCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1602            'order' => 'value DESC',
1603            'conditions' => [
1604                'user_id' => Auth::getUserID(),
1605                'category' => 'golden',
1606            ],
1607        ]);
1608        if (!$goldenCondition) {
1609            $goldenCondition = [];
1610            $goldenCondition['AchievementCondition']['value'] = 0;
1611            ClassRegistry::init('AchievementCondition')->create();
1612        }
1613        $goldenCondition['AchievementCondition']['category'] = 'golden';
1614        $goldenCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1615        if ($trigger) {
1616            $goldenCondition['AchievementCondition']['value']++;
1617        } else {
1618            $goldenCondition['AchievementCondition']['value'] = 0;
1619        }
1620        ClassRegistry::init('AchievementCondition')->save($goldenCondition);
1621    }
1622
1623    public static function setPotionCondition(): void {
1624        $potionCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1625            'order' => 'value DESC',
1626            'conditions' => [
1627                'user_id' => Auth::getUserID(),
1628                'category' => 'potion',
1629            ],
1630        ]);
1631        if (!$potionCondition) {
1632            $potionCondition = [];
1633            ClassRegistry::init('AchievementCondition')->create();
1634        }
1635        $potionCondition['AchievementCondition']['category'] = 'potion';
1636        $potionCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1637        $potionCondition['AchievementCondition']['value'] = 1;
1638        ClassRegistry::init('AchievementCondition')->save($potionCondition);
1639    }
1640
1641    public static function updateGems(string $rank): void {
1642        $datex = new DateTime('today');
1643        $dateGem = ClassRegistry::init('DayRecord')->find('first', ['conditions' => ['date' => $datex->format('Y-m-d')]]);
1644        if ($dateGem != null) {
1645            $gems = explode('-', $dateGem['DayRecord']['gems']);
1646            $gemValue = '';
1647            $gemValue2 = '';
1648            $gemValue3 = '';
1649            $condition1 = 500;
1650            $condition2 = 200;
1651            $condition3 = 5;
1652            $found1 = false;
1653            $found2 = false;
1654            $found3 = false;
1655            if ($rank == '15k' || $rank == '14k' || $rank == '13k' || $rank == '12k' || $rank == '11k' || $rank == '10k') {
1656                if ($gems[0] == 0) {
1657                    $gemValue = '15k';
1658                } elseif ($gems[0] == 1) {
1659                    $gemValue = '12k';
1660                } elseif ($gems[0] == 2) {
1661                    $gemValue = '10k';
1662                }
1663                if ($rank == $gemValue) {
1664                    $dateGem['DayRecord']['gemCounter1']++;
1665                    if ($dateGem['DayRecord']['gemCounter1'] == $condition1) {
1666                        $found1 = true;
1667                    }
1668                }
1669            } elseif ($rank == '9k' || $rank == '8k' || $rank == '7k' || $rank == '6k' || $rank == '5k' || $rank == '4k' || $rank == '3k' || $rank == '2k' || $rank == '1k') {
1670                if ($gems[1] == 0) {
1671                    $gemValue = '9k';
1672                    $gemValue2 = 'x';
1673                    $gemValue3 = 'y';
1674                } elseif ($gems[1] == 1) {
1675                    $gemValue = '6k';
1676                    $gemValue2 = '5k';
1677                    $gemValue3 = '4k';
1678                } elseif ($gems[1] == 2) {
1679                    $gemValue = 'x';
1680                    $gemValue2 = '2k';
1681                    $gemValue3 = '1k';
1682                }
1683                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
1684                    $dateGem['DayRecord']['gemCounter2']++;
1685                    if ($dateGem['DayRecord']['gemCounter2'] == $condition2) {
1686                        $found2 = true;
1687                    }
1688                }
1689            } elseif ($rank == '1d' || $rank == '2d' || $rank == '3d' || $rank == '4d' || $rank == '5d' || $rank == '6d' || $rank == '7d') {
1690                if ($gems[2] == 0) {
1691                    $gemValue = '1d';
1692                    $gemValue2 = '2d';
1693                    $gemValue3 = '3d';
1694                } elseif ($gems[2] == 1) {
1695                    $gemValue = '2d';
1696                    $gemValue2 = '3d';
1697                    $gemValue3 = '4d';
1698                } elseif ($gems[2] == 2) {
1699                    $gemValue = '5d';
1700                    $gemValue2 = '6d';
1701                    $gemValue3 = '7d';
1702                }
1703                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
1704                    $dateGem['DayRecord']['gemCounter3']++;
1705                    if ($dateGem['DayRecord']['gemCounter3'] == $condition3) {
1706                        $found3 = true;
1707                    }
1708                }
1709            }
1710            if ($found1) {
1711                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1712                    'order' => 'value DESC',
1713                    'conditions' => [
1714                        'user_id' => Auth::getUserID(),
1715                        'category' => 'emerald',
1716                    ],
1717                ]);
1718                if ($aCondition == null) {
1719                    $aCondition = [];
1720                    $aCondition['AchievementCondition']['category'] = 'emerald';
1721                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1722                    $aCondition['AchievementCondition']['value'] = 1;
1723                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1724                } else {
1725                    $dateGem['DayRecord']['gemCounter1']--;
1726                }
1727            } elseif ($found2) {
1728                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1729                    'order' => 'value DESC',
1730                    'conditions' => [
1731                        'user_id' => Auth::getUserID(),
1732                        'category' => 'sapphire',
1733                    ],
1734                ]);
1735                if ($aCondition == null) {
1736                    $aCondition = [];
1737                    $aCondition['AchievementCondition']['category'] = 'sapphire';
1738                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1739                    $aCondition['AchievementCondition']['value'] = 1;
1740                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1741                } else {
1742                    $dateGem['DayRecord']['gemCounter2']--;
1743                }
1744            } elseif ($found3) {
1745                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1746                    'order' => 'value DESC',
1747                    'conditions' => [
1748                        'user_id' => Auth::getUserID(),
1749                        'category' => 'ruby',
1750                    ],
1751                ]);
1752                if ($aCondition == null) {
1753                    $aCondition = [];
1754                    $aCondition['AchievementCondition']['category'] = 'ruby';
1755                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1756                    $aCondition['AchievementCondition']['value'] = 1;
1757                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1758                } else {
1759                    $dateGem['DayRecord']['gemCounter3']--;
1760                }
1761            }
1762        }
1763        ClassRegistry::init('DayRecord')->save($dateGem);
1764    }
1765
1766    public static function checkProblemNumberAchievements() {
1767        if (!Auth::isLoggedIn()) {
1768            return;
1769        }
1770
1771        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1772        if (!$buffer) {
1773            $buffer = [];
1774        }
1775        $existingAs = [];
1776        $bufferCount = count($buffer);
1777        for ($i = 0; $i < $bufferCount; $i++) {
1778            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1779        }
1780        $as = [];
1781        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1782        $updated = [];
1783
1784        $achievementId = 1;
1785        $solvedCount = Auth::getUser()['solved'];
1786        if ($solvedCount >= 1000 && !isset($existingAs[$achievementId])) {
1787            $as['AchievementStatus']['achievement_id'] = $achievementId;
1788            ClassRegistry::init('AchievementStatus')->create();
1789            ClassRegistry::init('AchievementStatus')->save($as);
1790            array_push($updated, $achievementId);
1791        }
1792        $achievementId = 2;
1793        if ($solvedCount >= 2000 && !isset($existingAs[$achievementId])) {
1794            $as['AchievementStatus']['achievement_id'] = $achievementId;
1795            ClassRegistry::init('AchievementStatus')->create();
1796            ClassRegistry::init('AchievementStatus')->save($as);
1797            array_push($updated, $achievementId);
1798        }
1799        $achievementId = 3;
1800        if ($solvedCount >= 3000 && !isset($existingAs[$achievementId])) {
1801            $as['AchievementStatus']['achievement_id'] = $achievementId;
1802            ClassRegistry::init('AchievementStatus')->create();
1803            ClassRegistry::init('AchievementStatus')->save($as);
1804            array_push($updated, $achievementId);
1805        }
1806        $achievementId = 4;
1807        if ($solvedCount >= 4000 && !isset($existingAs[$achievementId])) {
1808            $as['AchievementStatus']['achievement_id'] = $achievementId;
1809            ClassRegistry::init('AchievementStatus')->create();
1810            ClassRegistry::init('AchievementStatus')->save($as);
1811            array_push($updated, $achievementId);
1812        }
1813        $achievementId = 5;
1814        if ($solvedCount >= 5000 && !isset($existingAs[$achievementId])) {
1815            $as['AchievementStatus']['achievement_id'] = $achievementId;
1816            ClassRegistry::init('AchievementStatus')->create();
1817            ClassRegistry::init('AchievementStatus')->save($as);
1818            array_push($updated, $achievementId);
1819        }
1820        $achievementId = 6;
1821        if ($solvedCount >= 6000 && !isset($existingAs[$achievementId])) {
1822            $as['AchievementStatus']['achievement_id'] = $achievementId;
1823            ClassRegistry::init('AchievementStatus')->create();
1824            ClassRegistry::init('AchievementStatus')->save($as);
1825            array_push($updated, $achievementId);
1826        }
1827        $achievementId = 7;
1828        if ($solvedCount >= 7000 && !isset($existingAs[$achievementId])) {
1829            $as['AchievementStatus']['achievement_id'] = $achievementId;
1830            ClassRegistry::init('AchievementStatus')->create();
1831            ClassRegistry::init('AchievementStatus')->save($as);
1832            array_push($updated, $achievementId);
1833        }
1834        $achievementId = 8;
1835        if ($solvedCount >= 8000 && !isset($existingAs[$achievementId])) {
1836            $as['AchievementStatus']['achievement_id'] = $achievementId;
1837            ClassRegistry::init('AchievementStatus')->create();
1838            ClassRegistry::init('AchievementStatus')->save($as);
1839            array_push($updated, $achievementId);
1840        }
1841        $achievementId = 9;
1842        if ($solvedCount >= 9000 && !isset($existingAs[$achievementId])) {
1843            $as['AchievementStatus']['achievement_id'] = $achievementId;
1844            ClassRegistry::init('AchievementStatus')->create();
1845            ClassRegistry::init('AchievementStatus')->save($as);
1846            array_push($updated, $achievementId);
1847        }
1848        $achievementId = 10;
1849        if ($solvedCount >= 10000 && !isset($existingAs[$achievementId])) {
1850            $as['AchievementStatus']['achievement_id'] = $achievementId;
1851            ClassRegistry::init('AchievementStatus')->create();
1852            ClassRegistry::init('AchievementStatus')->save($as);
1853            array_push($updated, $achievementId);
1854        }
1855        //uotd achievement
1856        $achievementId = 11;
1857        if (!isset($existingAs[$achievementId])) {
1858            $condition = ClassRegistry::init('AchievementCondition')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => 'uotd']]);
1859            if ($condition != null) {
1860                $as['AchievementStatus']['achievement_id'] = $achievementId;
1861                ClassRegistry::init('AchievementStatus')->create();
1862                ClassRegistry::init('AchievementStatus')->save($as);
1863                array_push($updated, $achievementId);
1864            }
1865        }
1866
1867        $updatedCount = count($updated);
1868        for ($i = 0; $i < $updatedCount; $i++) {
1869            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1870            $updated[$i] = [];
1871            $updated[$i][0] = $a['Achievement']['name'];
1872            $updated[$i][1] = $a['Achievement']['description'];
1873            $updated[$i][2] = $a['Achievement']['image'];
1874            $updated[$i][3] = $a['Achievement']['color'];
1875            $updated[$i][4] = $a['Achievement']['xp'];
1876            $updated[$i][5] = $a['Achievement']['id'];
1877        }
1878
1879        return $updated;
1880    }
1881
1882    public static function checkDanSolveAchievements() {
1883        if (Auth::isLoggedIn()) {
1884            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1885            if (!$buffer) {
1886                $buffer = [];
1887            }
1888            $ac = ClassRegistry::init('AchievementCondition')->find('all', [
1889                'order' => 'category ASC',
1890                'conditions' => [
1891                    'user_id' => Auth::getUserID(),
1892                    'OR' => [
1893                        ['category' => 'danSolve1d'],
1894                        ['category' => 'danSolve2d'],
1895                        ['category' => 'danSolve3d'],
1896                        ['category' => 'danSolve4d'],
1897                        ['category' => 'danSolve5d'],
1898                        ['category' => 'emerald'],
1899                        ['category' => 'sapphire'],
1900                        ['category' => 'ruby'],
1901                        ['category' => 'sprint'],
1902                        ['category' => 'golden'],
1903                        ['category' => 'potion'],
1904                    ],
1905                ],
1906            ]);
1907            if (!$ac) {
1908                $ac = [];
1909            }
1910            $ac1 = [];
1911            $acCount = count($ac);
1912            for ($i = 0; $i < $acCount; $i++) {
1913                if ($ac[$i]['AchievementCondition']['category'] == 'danSolve1d') {
1914                    $ac1['1d'] = $ac[$i]['AchievementCondition']['value'];
1915                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve2d') {
1916                    $ac1['2d'] = $ac[$i]['AchievementCondition']['value'];
1917                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve3d') {
1918                    $ac1['3d'] = $ac[$i]['AchievementCondition']['value'];
1919                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve4d') {
1920                    $ac1['4d'] = $ac[$i]['AchievementCondition']['value'];
1921                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve5d') {
1922                    $ac1['5d'] = $ac[$i]['AchievementCondition']['value'];
1923                } elseif ($ac[$i]['AchievementCondition']['category'] == 'emerald') {
1924                    $ac1['emerald'] = $ac[$i]['AchievementCondition']['value'];
1925                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sapphire') {
1926                    $ac1['sapphire'] = $ac[$i]['AchievementCondition']['value'];
1927                } elseif ($ac[$i]['AchievementCondition']['category'] == 'ruby') {
1928                    $ac1['ruby'] = $ac[$i]['AchievementCondition']['value'];
1929                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sprint') {
1930                    $ac1['sprint'] = $ac[$i]['AchievementCondition']['value'];
1931                } elseif ($ac[$i]['AchievementCondition']['category'] == 'golden') {
1932                    $ac1['golden'] = $ac[$i]['AchievementCondition']['value'];
1933                } elseif ($ac[$i]['AchievementCondition']['category'] == 'potion') {
1934                    $ac1['potion'] = $ac[$i]['AchievementCondition']['value'];
1935                }
1936            }
1937
1938            $existingAs = [];
1939            $bufferCount = count($buffer);
1940            for ($i = 0; $i < $bufferCount; $i++) {
1941                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1942            }
1943            $as = [];
1944            $as['AchievementStatus']['user_id'] = Auth::getUserID();
1945            $updated = [];
1946            $achievementId = 101;
1947            if ($ac1['1d'] > 0 && !isset($existingAs[$achievementId])) {
1948                $as['AchievementStatus']['achievement_id'] = $achievementId;
1949                ClassRegistry::init('AchievementStatus')->create();
1950                ClassRegistry::init('AchievementStatus')->save($as);
1951                array_push($updated, $achievementId);
1952            }
1953            $achievementId = 102;
1954            if ($ac1['2d'] > 0 && !isset($existingAs[$achievementId])) {
1955                $as['AchievementStatus']['achievement_id'] = $achievementId;
1956                ClassRegistry::init('AchievementStatus')->create();
1957                ClassRegistry::init('AchievementStatus')->save($as);
1958                array_push($updated, $achievementId);
1959            }
1960            $achievementId = 103;
1961            if ($ac1['3d'] > 0 && !isset($existingAs[$achievementId])) {
1962                $as['AchievementStatus']['achievement_id'] = $achievementId;
1963                ClassRegistry::init('AchievementStatus')->create();
1964                ClassRegistry::init('AchievementStatus')->save($as);
1965                array_push($updated, $achievementId);
1966            }
1967            $achievementId = 104;
1968            if ($ac1['4d'] > 0 && !isset($existingAs[$achievementId])) {
1969                $as['AchievementStatus']['achievement_id'] = $achievementId;
1970                ClassRegistry::init('AchievementStatus')->create();
1971                ClassRegistry::init('AchievementStatus')->save($as);
1972                array_push($updated, $achievementId);
1973            }
1974            $achievementId = 105;
1975            if ($ac1['5d'] > 0 && !isset($existingAs[$achievementId])) {
1976                $as['AchievementStatus']['achievement_id'] = $achievementId;
1977                ClassRegistry::init('AchievementStatus')->create();
1978                ClassRegistry::init('AchievementStatus')->save($as);
1979                array_push($updated, $achievementId);
1980            }
1981            $achievementId = 106;
1982            if ($ac1['1d'] >= 10 && !isset($existingAs[$achievementId])) {
1983                $as['AchievementStatus']['achievement_id'] = $achievementId;
1984                ClassRegistry::init('AchievementStatus')->create();
1985                ClassRegistry::init('AchievementStatus')->save($as);
1986                array_push($updated, $achievementId);
1987            }
1988            $achievementId = 107;
1989            if ($ac1['2d'] >= 10 && !isset($existingAs[$achievementId])) {
1990                $as['AchievementStatus']['achievement_id'] = $achievementId;
1991                ClassRegistry::init('AchievementStatus')->create();
1992                ClassRegistry::init('AchievementStatus')->save($as);
1993                array_push($updated, $achievementId);
1994            }
1995            $achievementId = 108;
1996            if ($ac1['3d'] >= 10 && !isset($existingAs[$achievementId])) {
1997                $as['AchievementStatus']['achievement_id'] = $achievementId;
1998                ClassRegistry::init('AchievementStatus')->create();
1999                ClassRegistry::init('AchievementStatus')->save($as);
2000                array_push($updated, $achievementId);
2001            }
2002            $achievementId = 109;
2003            if ($ac1['4d'] >= 10 && !isset($existingAs[$achievementId])) {
2004                $as['AchievementStatus']['achievement_id'] = $achievementId;
2005                ClassRegistry::init('AchievementStatus')->create();
2006                ClassRegistry::init('AchievementStatus')->save($as);
2007                array_push($updated, $achievementId);
2008            }
2009            $achievementId = 110;
2010            if ($ac1['5d'] >= 10 && !isset($existingAs[$achievementId])) {
2011                $as['AchievementStatus']['achievement_id'] = $achievementId;
2012                ClassRegistry::init('AchievementStatus')->create();
2013                ClassRegistry::init('AchievementStatus')->save($as);
2014                array_push($updated, $achievementId);
2015            }
2016            $achievementId = 111;
2017            if (isset($ac1['emerald'])) {
2018                if ($ac1['emerald'] == 1 && !isset($existingAs[$achievementId])) {
2019                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2020                    ClassRegistry::init('AchievementStatus')->create();
2021                    ClassRegistry::init('AchievementStatus')->save($as);
2022                    array_push($updated, $achievementId);
2023                }
2024            }
2025            $achievementId = 112;
2026            if (isset($ac1['sapphire'])) {
2027                if ($ac1['sapphire'] == 1 && !isset($existingAs[$achievementId])) {
2028                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2029                    ClassRegistry::init('AchievementStatus')->create();
2030                    ClassRegistry::init('AchievementStatus')->save($as);
2031                    array_push($updated, $achievementId);
2032                }
2033            }
2034            $achievementId = 113;
2035            if (isset($ac1['ruby'])) {
2036                if ($ac1['ruby'] == 1 && !isset($existingAs[$achievementId])) {
2037                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2038                    ClassRegistry::init('AchievementStatus')->create();
2039                    ClassRegistry::init('AchievementStatus')->save($as);
2040                    array_push($updated, $achievementId);
2041                }
2042            }
2043            $achievementId = 114;
2044            if (!isset($existingAs[$achievementId]) && isset($existingAs[111]) && isset($existingAs[112]) && isset($existingAs[113])) {
2045                $as['AchievementStatus']['achievement_id'] = $achievementId;
2046                ClassRegistry::init('AchievementStatus')->create();
2047                ClassRegistry::init('AchievementStatus')->save($as);
2048                array_push($updated, $achievementId);
2049            }
2050            $achievementId = 96;
2051            if (!isset($existingAs[$achievementId]) && $ac1['sprint'] >= 30) {
2052                $as['AchievementStatus']['achievement_id'] = $achievementId;
2053                ClassRegistry::init('AchievementStatus')->create();
2054                ClassRegistry::init('AchievementStatus')->save($as);
2055                array_push($updated, $achievementId);
2056            }
2057            $achievementId = 97;
2058            if (!isset($existingAs[$achievementId]) && $ac1['golden'] >= 10) {
2059                $as['AchievementStatus']['achievement_id'] = $achievementId;
2060                ClassRegistry::init('AchievementStatus')->create();
2061                ClassRegistry::init('AchievementStatus')->save($as);
2062                array_push($updated, $achievementId);
2063            }
2064            $achievementId = 98;
2065            if (!isset($existingAs[$achievementId]) && $ac1['potion'] >= 1) {
2066                $as['AchievementStatus']['achievement_id'] = $achievementId;
2067                ClassRegistry::init('AchievementStatus')->create();
2068                ClassRegistry::init('AchievementStatus')->save($as);
2069                array_push($updated, $achievementId);
2070            }
2071            $updatedCount = count($updated);
2072            for ($i = 0; $i < $updatedCount; $i++) {
2073                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2074                $updated[$i] = [];
2075                $updated[$i][0] = $a['Achievement']['name'];
2076                $updated[$i][1] = $a['Achievement']['description'];
2077                $updated[$i][2] = $a['Achievement']['image'];
2078                $updated[$i][3] = $a['Achievement']['color'];
2079                $updated[$i][4] = $a['Achievement']['xp'];
2080                $updated[$i][5] = $a['Achievement']['id'];
2081            }
2082
2083            return $updated;
2084        }
2085    }
2086
2087    protected function checkForLocked($t, $setsWithPremium) {
2088        $scCheck = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $t['Tsumego']['id']]]);
2089        if ($scCheck && in_array($scCheck['SetConnection']['set_id'], $setsWithPremium) && !Auth::hasPremium()) {
2090            $t['Tsumego']['locked'] = true;
2091        } else {
2092            $t['Tsumego']['locked'] = false;
2093        }
2094
2095        return $t;
2096    }
2097    public static function checkNoErrorAchievements() {
2098        if (Auth::isLoggedIn()) {
2099
2100            $ac = ClassRegistry::init('AchievementCondition')->find('first', [
2101                'order' => 'value DESC',
2102                'conditions' => [
2103                    'user_id' => Auth::getUserID(),
2104                    'category' => 'err',
2105                ],
2106            ]);
2107
2108            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2109            if (!$buffer) {
2110                $buffer = [];
2111            }
2112            $existingAs = [];
2113            $bufferCount = count($buffer);
2114            for ($i = 0; $i < $bufferCount; $i++) {
2115                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2116            }
2117            $as = [];
2118            $as['AchievementStatus']['user_id'] = Auth::getUserID();
2119            $updated = [];
2120
2121            $achievementId = 53;
2122            if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
2123                $as['AchievementStatus']['achievement_id'] = $achievementId;
2124                ClassRegistry::init('AchievementStatus')->create();
2125                ClassRegistry::init('AchievementStatus')->save($as);
2126                array_push($updated, $achievementId);
2127            }
2128            $achievementId = 54;
2129            if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
2130                $as['AchievementStatus']['achievement_id'] = $achievementId;
2131                ClassRegistry::init('AchievementStatus')->create();
2132                ClassRegistry::init('AchievementStatus')->save($as);
2133                array_push($updated, $achievementId);
2134            }
2135            $achievementId = 55;
2136            if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
2137                $as['AchievementStatus']['achievement_id'] = $achievementId;
2138                ClassRegistry::init('AchievementStatus')->create();
2139                ClassRegistry::init('AchievementStatus')->save($as);
2140                array_push($updated, $achievementId);
2141            }
2142            $achievementId = 56;
2143            if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
2144                $as['AchievementStatus']['achievement_id'] = $achievementId;
2145                ClassRegistry::init('AchievementStatus')->create();
2146                ClassRegistry::init('AchievementStatus')->save($as);
2147                array_push($updated, $achievementId);
2148            }
2149            $achievementId = 57;
2150            if ($ac['AchievementCondition']['value'] >= 100 && !isset($existingAs[$achievementId])) {
2151                $as['AchievementStatus']['achievement_id'] = $achievementId;
2152                ClassRegistry::init('AchievementStatus')->create();
2153                ClassRegistry::init('AchievementStatus')->save($as);
2154                array_push($updated, $achievementId);
2155            }
2156            $achievementId = 58;
2157            if ($ac['AchievementCondition']['value'] >= 200 && !isset($existingAs[$achievementId])) {
2158                $as['AchievementStatus']['achievement_id'] = $achievementId;
2159                ClassRegistry::init('AchievementStatus')->create();
2160                ClassRegistry::init('AchievementStatus')->save($as);
2161                array_push($updated, $achievementId);
2162            }
2163            $updatedCount = count($updated);
2164            for ($i = 0; $i < $updatedCount; $i++) {
2165                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2166                $updated[$i] = [];
2167                $updated[$i][0] = $a['Achievement']['name'];
2168                $updated[$i][1] = $a['Achievement']['description'];
2169                $updated[$i][2] = $a['Achievement']['image'];
2170                $updated[$i][3] = $a['Achievement']['color'];
2171                $updated[$i][4] = $a['Achievement']['xp'];
2172                $updated[$i][5] = $a['Achievement']['id'];
2173            }
2174
2175            return $updated;
2176        }
2177    }
2178
2179    protected function checkTimeModeAchievements() {
2180        $this->loadModel('Achievement');
2181        $this->loadModel('AchievementStatus');
2182        $this->loadModel('TimeModeSession');
2183
2184        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2185        if (!$buffer) {
2186            $buffer = [];
2187        }
2188        $existingAs = [];
2189        $bufferCount = count($buffer);
2190        for ($i = 0; $i < $bufferCount; $i++) {
2191            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2192        }
2193        $as = [];
2194        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2195        $updated = [];
2196
2197        $rBlitz = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_BLITZ, 'user_id' => Auth::getUserID()]]);
2198        if (!$rBlitz) {
2199            $rBlitz = [];
2200        }
2201        $rFast = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_FAST_SPEED, 'user_id' => Auth::getUserID()]]);
2202        if (!$rFast) {
2203            $rFast = [];
2204        }
2205        $rSlow = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_SLOW_SPEED, 'user_id' => Auth::getUserID()]]);
2206        if (!$rSlow) {
2207            $rSlow = [];
2208        }
2209        $r = $this->TimeModeSession->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2210        if (!$r) {
2211            $r = [];
2212        }
2213
2214        $timeModeAchievements = [];
2215        for ($i = 70; $i <= 91; $i++) {
2216            $timeModeAchievements[$i] = false;
2217        }
2218        $rCount = count($r);
2219        for ($i = 0; $i < $rCount; $i++) {
2220            if ($r[$i]['TimeModeSession']['status'] == 's') {
2221                if ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k') {
2222                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2223                        $timeModeAchievements[70] = true;
2224                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2225                        $timeModeAchievements[76] = true;
2226                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2227                        $timeModeAchievements[82] = true;
2228                    }
2229                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k') {
2230                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2231                        $timeModeAchievements[71] = true;
2232                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2233                        $timeModeAchievements[77] = true;
2234                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2235                        $timeModeAchievements[83] = true;
2236                    }
2237                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k') {
2238                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2239                        $timeModeAchievements[72] = true;
2240                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2241                        $timeModeAchievements[78] = true;
2242                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2243                        $timeModeAchievements[84] = true;
2244                    }
2245                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k') {
2246                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2247                        $timeModeAchievements[73] = true;
2248                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2249                        $timeModeAchievements[79] = true;
2250                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2251                        $timeModeAchievements[85] = true;
2252                    }
2253                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k') {
2254                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2255                        $timeModeAchievements[74] = true;
2256                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2257                        $timeModeAchievements[80] = true;
2258                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2259                        $timeModeAchievements[86] = true;
2260                    }
2261                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d') {
2262                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2263                        $timeModeAchievements[75] = true;
2264                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2265                        $timeModeAchievements[81] = true;
2266                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2267                        $timeModeAchievements[87] = true;
2268                    }
2269                }
2270            }
2271            if ($r[$i]['TimeModeSession']['points'] >= 850
2272            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
2273            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
2274            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d')) {
2275                $timeModeAchievements[91] = true;
2276            }
2277            if ($r[$i]['TimeModeSession']['points'] >= 875
2278            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
2279            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
2280            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k')) {
2281                $timeModeAchievements[90] = true;
2282            }
2283            if ($r[$i]['TimeModeSession']['points'] >= 900
2284            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
2285            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
2286            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
2287            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k')) {
2288                $timeModeAchievements[89] = true;
2289            }
2290            if ($r[$i]['TimeModeSession']['points'] >= 950
2291            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
2292            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
2293            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
2294            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '9k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '10k')) {
2295                $timeModeAchievements[88] = true;
2296            }
2297        }
2298        for ($i = 70; $i <= 91; $i++) {
2299            $achievementId = $i;
2300            if ($timeModeAchievements[$achievementId] == true && !isset($existingAs[$achievementId])) {
2301                $as['AchievementStatus']['achievement_id'] = $achievementId;
2302                ClassRegistry::init('AchievementStatus')->create();
2303                ClassRegistry::init('AchievementStatus')->save($as);
2304                array_push($updated, $achievementId);
2305            }
2306        }
2307        $updatedCount = count($updated);
2308        for ($i = 0; $i < $updatedCount; $i++) {
2309            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2310            $updated[$i] = [];
2311            $updated[$i][0] = $a['Achievement']['name'];
2312            $updated[$i][1] = $a['Achievement']['description'];
2313            $updated[$i][2] = $a['Achievement']['image'];
2314            $updated[$i][3] = $a['Achievement']['color'];
2315            $updated[$i][4] = $a['Achievement']['xp'];
2316            $updated[$i][5] = $a['Achievement']['id'];
2317        }
2318
2319        return $updated;
2320    }
2321
2322    public static function checkRatingAchievements() {
2323        if (!Auth::isLoggedIn()) {
2324            return;
2325        }
2326
2327        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2328        if (!$buffer) {
2329            $buffer = [];
2330        }
2331        $existingAs = [];
2332        $bufferCount = count($buffer);
2333        for ($i = 0; $i < $bufferCount; $i++) {
2334            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2335        }
2336        $as = [];
2337        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2338        $updated = [];
2339
2340        $achievementId = 59;
2341        $currentElo = Auth::getUser()['rating'];
2342        if ($currentElo >= 1500 && !isset($existingAs[$achievementId])) {
2343            $as['AchievementStatus']['achievement_id'] = $achievementId;
2344            ClassRegistry::init('AchievementStatus')->create();
2345            ClassRegistry::init('AchievementStatus')->save($as);
2346            array_push($updated, $achievementId);
2347        }
2348        $achievementId = 60;
2349        if ($currentElo >= 1600 && !isset($existingAs[$achievementId])) {
2350            $as['AchievementStatus']['achievement_id'] = $achievementId;
2351            ClassRegistry::init('AchievementStatus')->create();
2352            ClassRegistry::init('AchievementStatus')->save($as);
2353            array_push($updated, $achievementId);
2354        }
2355        $achievementId = 61;
2356        if ($currentElo >= 1700 && !isset($existingAs[$achievementId])) {
2357            $as['AchievementStatus']['achievement_id'] = $achievementId;
2358            ClassRegistry::init('AchievementStatus')->create();
2359            ClassRegistry::init('AchievementStatus')->save($as);
2360            array_push($updated, $achievementId);
2361        }
2362        $achievementId = 62;
2363        if ($currentElo >= 1800 && !isset($existingAs[$achievementId])) {
2364            $as['AchievementStatus']['achievement_id'] = $achievementId;
2365            ClassRegistry::init('AchievementStatus')->create();
2366            ClassRegistry::init('AchievementStatus')->save($as);
2367            array_push($updated, $achievementId);
2368        }
2369        $achievementId = 63;
2370        if ($currentElo >= 1900 && !isset($existingAs[$achievementId])) {
2371            $as['AchievementStatus']['achievement_id'] = $achievementId;
2372            ClassRegistry::init('AchievementStatus')->create();
2373            ClassRegistry::init('AchievementStatus')->save($as);
2374            array_push($updated, $achievementId);
2375        }
2376        $achievementId = 64;
2377        if ($currentElo >= 2000 && !isset($existingAs[$achievementId])) {
2378            $as['AchievementStatus']['achievement_id'] = $achievementId;
2379            ClassRegistry::init('AchievementStatus')->create();
2380            ClassRegistry::init('AchievementStatus')->save($as);
2381            array_push($updated, $achievementId);
2382        }
2383        $achievementId = 65;
2384        if ($currentElo >= 2100 && !isset($existingAs[$achievementId])) {
2385            $as['AchievementStatus']['achievement_id'] = $achievementId;
2386            ClassRegistry::init('AchievementStatus')->create();
2387            ClassRegistry::init('AchievementStatus')->save($as);
2388            array_push($updated, $achievementId);
2389        }
2390        $achievementId = 66;
2391        if ($currentElo >= 2200 && !isset($existingAs[$achievementId])) {
2392            $as['AchievementStatus']['achievement_id'] = $achievementId;
2393            ClassRegistry::init('AchievementStatus')->create();
2394            ClassRegistry::init('AchievementStatus')->save($as);
2395            array_push($updated, $achievementId);
2396        }
2397        $achievementId = 67;
2398        if ($currentElo >= 2300 && !isset($existingAs[$achievementId])) {
2399            $as['AchievementStatus']['achievement_id'] = $achievementId;
2400            ClassRegistry::init('AchievementStatus')->create();
2401            ClassRegistry::init('AchievementStatus')->save($as);
2402            array_push($updated, $achievementId);
2403        }
2404        $achievementId = 68;
2405        if ($currentElo >= 2400 && !isset($existingAs[$achievementId])) {
2406            $as['AchievementStatus']['achievement_id'] = $achievementId;
2407            ClassRegistry::init('AchievementStatus')->create();
2408            ClassRegistry::init('AchievementStatus')->save($as);
2409            array_push($updated, $achievementId);
2410        }
2411        $achievementId = 69;
2412        if ($currentElo >= 2500 && !isset($existingAs[$achievementId])) {
2413            $as['AchievementStatus']['achievement_id'] = $achievementId;
2414            ClassRegistry::init('AchievementStatus')->create();
2415            ClassRegistry::init('AchievementStatus')->save($as);
2416            array_push($updated, $achievementId);
2417        }
2418        $updatedCount = count($updated);
2419        for ($i = 0; $i < $updatedCount; $i++) {
2420            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2421            $updated[$i] = [];
2422            $updated[$i][0] = $a['Achievement']['name'];
2423            $updated[$i][1] = $a['Achievement']['description'];
2424            $updated[$i][2] = $a['Achievement']['image'];
2425            $updated[$i][3] = $a['Achievement']['color'];
2426            $updated[$i][4] = $a['Achievement']['xp'];
2427            $updated[$i][5] = $a['Achievement']['id'];
2428        }
2429
2430        return $updated;
2431    }
2432
2433    public static function checkLevelAchievements() {
2434        if (!Auth::isLoggedIn()) {
2435            return;
2436        }
2437        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2438        if (!$buffer) {
2439            $buffer = [];
2440        }
2441        $existingAs = [];
2442        $bufferCount = count($buffer);
2443        for ($i = 0; $i < $bufferCount; $i++) {
2444            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2445        }
2446        $as = [];
2447        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2448        $updated = [];
2449
2450        $achievementId = 36;
2451        $userLevel = Auth::getUser()['level'];
2452        if ($userLevel >= 10 && !isset($existingAs[$achievementId])) {
2453            $as['AchievementStatus']['achievement_id'] = $achievementId;
2454            ClassRegistry::init('AchievementStatus')->create();
2455            ClassRegistry::init('AchievementStatus')->save($as);
2456            array_push($updated, $achievementId);
2457        }
2458        $achievementId = 37;
2459        if ($userLevel >= 20 && !isset($existingAs[$achievementId])) {
2460            $as['AchievementStatus']['achievement_id'] = $achievementId;
2461            ClassRegistry::init('AchievementStatus')->create();
2462            ClassRegistry::init('AchievementStatus')->save($as);
2463            array_push($updated, $achievementId);
2464        }
2465        $achievementId = 38;
2466        if ($userLevel >= 30 && !isset($existingAs[$achievementId])) {
2467            $as['AchievementStatus']['achievement_id'] = $achievementId;
2468            ClassRegistry::init('AchievementStatus')->create();
2469            ClassRegistry::init('AchievementStatus')->save($as);
2470            array_push($updated, $achievementId);
2471        }
2472        $achievementId = 39;
2473        if ($userLevel >= 40 && !isset($existingAs[$achievementId])) {
2474            $as['AchievementStatus']['achievement_id'] = $achievementId;
2475            ClassRegistry::init('AchievementStatus')->create();
2476            ClassRegistry::init('AchievementStatus')->save($as);
2477            array_push($updated, $achievementId);
2478        }
2479        $achievementId = 40;
2480        if ($userLevel >= 50 && !isset($existingAs[$achievementId])) {
2481            $as['AchievementStatus']['achievement_id'] = $achievementId;
2482            ClassRegistry::init('AchievementStatus')->create();
2483            ClassRegistry::init('AchievementStatus')->save($as);
2484            array_push($updated, $achievementId);
2485        }
2486        $achievementId = 41;
2487        if ($userLevel >= 60 && !isset($existingAs[$achievementId])) {
2488            $as['AchievementStatus']['achievement_id'] = $achievementId;
2489            ClassRegistry::init('AchievementStatus')->create();
2490            ClassRegistry::init('AchievementStatus')->save($as);
2491            array_push($updated, $achievementId);
2492        }
2493        $achievementId = 42;
2494        if ($userLevel >= 70 && !isset($existingAs[$achievementId])) {
2495            $as['AchievementStatus']['achievement_id'] = $achievementId;
2496            ClassRegistry::init('AchievementStatus')->create();
2497            ClassRegistry::init('AchievementStatus')->save($as);
2498            array_push($updated, $achievementId);
2499        }
2500        $achievementId = 43;
2501        if ($userLevel >= 80 && !isset($existingAs[$achievementId])) {
2502            $as['AchievementStatus']['achievement_id'] = $achievementId;
2503            ClassRegistry::init('AchievementStatus')->create();
2504            ClassRegistry::init('AchievementStatus')->save($as);
2505            array_push($updated, $achievementId);
2506        }
2507        $achievementId = 44;
2508        if ($userLevel >= 90 && !isset($existingAs[$achievementId])) {
2509            $as['AchievementStatus']['achievement_id'] = $achievementId;
2510            ClassRegistry::init('AchievementStatus')->create();
2511            ClassRegistry::init('AchievementStatus')->save($as);
2512            array_push($updated, $achievementId);
2513        }
2514        $achievementId = 45;
2515        if ($userLevel >= 100 && !isset($existingAs[$achievementId])) {
2516            $as['AchievementStatus']['achievement_id'] = $achievementId;
2517            ClassRegistry::init('AchievementStatus')->create();
2518            ClassRegistry::init('AchievementStatus')->save($as);
2519            array_push($updated, $achievementId);
2520        }
2521        $achievementId = 100;
2522        if (Auth::hasPremium() && !isset($existingAs[$achievementId])) {
2523            $as['AchievementStatus']['achievement_id'] = $achievementId;
2524            ClassRegistry::init('AchievementStatus')->create();
2525            ClassRegistry::init('AchievementStatus')->save($as);
2526            array_push($updated, $achievementId);
2527        }
2528        $updatedCount = count($updated);
2529        for ($i = 0; $i < $updatedCount; $i++) {
2530            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2531            $updated[$i] = [];
2532            $updated[$i][0] = $a['Achievement']['name'];
2533            $updated[$i][1] = $a['Achievement']['description'];
2534            $updated[$i][2] = $a['Achievement']['image'];
2535            $updated[$i][3] = $a['Achievement']['color'];
2536            $updated[$i][4] = $a['Achievement']['xp'];
2537            $updated[$i][5] = $a['Achievement']['id'];
2538        }
2539
2540        return $updated;
2541    }
2542
2543    protected function checkSetCompletedAchievements() {
2544        $this->loadModel('Set');
2545        $this->loadModel('Tsumego');
2546        $this->loadModel('Achievement');
2547        $this->loadModel('AchievementStatus');
2548        $this->loadModel('AchievementCondition');
2549
2550        $ac = ClassRegistry::init('AchievementCondition')->find('first', [
2551            'order' => 'value DESC',
2552            'conditions' => [
2553                'user_id' => Auth::getUserID(),
2554                'category' => 'set',
2555            ],
2556        ]);
2557
2558        if (!$ac) {
2559            return [];
2560        }
2561
2562        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2563        if (!$buffer) {
2564            $buffer = [];
2565        }
2566        $existingAs = [];
2567        $bufferCount = count($buffer);
2568        for ($i = 0; $i < $bufferCount; $i++) {
2569            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2570        }
2571        $as = [];
2572        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2573        $updated = [];
2574
2575        $achievementId = 47;
2576        if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
2577            $as['AchievementStatus']['achievement_id'] = $achievementId;
2578            ClassRegistry::init('AchievementStatus')->create();
2579            ClassRegistry::init('AchievementStatus')->save($as);
2580            array_push($updated, $achievementId);
2581        }
2582        $achievementId = 48;
2583        if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
2584            $as['AchievementStatus']['achievement_id'] = $achievementId;
2585            ClassRegistry::init('AchievementStatus')->create();
2586            ClassRegistry::init('AchievementStatus')->save($as);
2587            array_push($updated, $achievementId);
2588        }
2589        $achievementId = 49;
2590        if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
2591            $as['AchievementStatus']['achievement_id'] = $achievementId;
2592            ClassRegistry::init('AchievementStatus')->create();
2593            ClassRegistry::init('AchievementStatus')->save($as);
2594            array_push($updated, $achievementId);
2595        }
2596        $achievementId = 50;
2597        if ($ac['AchievementCondition']['value'] >= 40 && !isset($existingAs[$achievementId])) {
2598            $as['AchievementStatus']['achievement_id'] = $achievementId;
2599            ClassRegistry::init('AchievementStatus')->create();
2600            ClassRegistry::init('AchievementStatus')->save($as);
2601            array_push($updated, $achievementId);
2602        }
2603        $achievementId = 51;
2604        if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
2605            $as['AchievementStatus']['achievement_id'] = $achievementId;
2606            ClassRegistry::init('AchievementStatus')->create();
2607            ClassRegistry::init('AchievementStatus')->save($as);
2608            array_push($updated, $achievementId);
2609        }
2610        $achievementId = 52;
2611        if ($ac['AchievementCondition']['value'] >= 60 && !isset($existingAs[$achievementId])) {
2612            $as['AchievementStatus']['achievement_id'] = $achievementId;
2613            ClassRegistry::init('AchievementStatus')->create();
2614            ClassRegistry::init('AchievementStatus')->save($as);
2615            array_push($updated, $achievementId);
2616        }
2617        $updatedCount = count($updated);
2618        for ($i = 0; $i < $updatedCount; $i++) {
2619            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2620            $updated[$i] = [];
2621            $updated[$i][0] = $a['Achievement']['name'];
2622            $updated[$i][1] = $a['Achievement']['description'];
2623            $updated[$i][2] = $a['Achievement']['image'];
2624            $updated[$i][3] = $a['Achievement']['color'];
2625            $updated[$i][4] = $a['Achievement']['xp'];
2626            $updated[$i][5] = $a['Achievement']['id'];
2627        }
2628
2629        return $updated;
2630    }
2631
2632    protected function setAchievementSpecial($s = null) {
2633        $this->loadModel('Set');
2634        $this->loadModel('Tsumego');
2635        $this->loadModel('TsumegoStatus');
2636        $this->loadModel('Achievement');
2637        $this->loadModel('AchievementStatus');
2638        $this->loadModel('SetConnection');
2639
2640        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2641        if (!$buffer) {
2642            $buffer = [];
2643        }
2644        $existingAs = [];
2645        $bufferCount = count($buffer);
2646        for ($i = 0; $i < $bufferCount; $i++) {
2647            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2648        }
2649        $as = [];
2650        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2651        $updated = [];
2652
2653        $tsIds = [];
2654        $completed = '';
2655        if ($s == 'cc1') {
2656            $ts1 = TsumegoUtil::collectTsumegosFromSet(50);
2657            $ts2 = TsumegoUtil::collectTsumegosFromSet(52);
2658            $ts3 = TsumegoUtil::collectTsumegosFromSet(53);
2659            $ts4 = TsumegoUtil::collectTsumegosFromSet(54);
2660            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2661            $tsCount = count($ts);
2662            for ($i = 0; $i < $tsCount; $i++) {
2663                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2664            }
2665            $uts = $this->TsumegoStatus->find('all', [
2666                'conditions' => [
2667                    'user_id' => Auth::getUserID(),
2668                    'tsumego_id' => $tsIds,
2669                ],
2670            ]);
2671            if (!$uts) {
2672                $uts = [];
2673            }
2674            $counter = 0;
2675            $utsCount = count($uts);
2676            for ($j = 0; $j < $utsCount; $j++) {
2677                for ($k = 0; $k < $tsCount; $k++) {
2678                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2679                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2680                        $counter++;
2681                    }
2682                }
2683            }
2684            if ($counter == count($ts)) {
2685                $completed = $s;
2686            }
2687        } elseif ($s == 'cc2') {
2688            $ts1 = TsumegoUtil::collectTsumegosFromSet(41);
2689            $ts2 = TsumegoUtil::collectTsumegosFromSet(49);
2690            $ts3 = TsumegoUtil::collectTsumegosFromSet(65);
2691            $ts4 = TsumegoUtil::collectTsumegosFromSet(66);
2692            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2693            $tsCount = count($ts);
2694            for ($i = 0; $i < $tsCount; $i++) {
2695                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2696            }
2697            $uts = $this->TsumegoStatus->find('all', [
2698                'conditions' => [
2699                    'user_id' => Auth::getUserID(),
2700                    'tsumego_id' => $tsIds,
2701                ],
2702            ]);
2703            if (!$uts) {
2704                $uts = [];
2705            }
2706            $counter = 0;
2707            $utsCount = count($uts);
2708            for ($j = 0; $j < $utsCount; $j++) {
2709                for ($k = 0; $k < $tsCount; $k++) {
2710                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2711                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2712                        $counter++;
2713                    }
2714                }
2715            }
2716            if ($counter == count($ts)) {
2717                $completed = $s;
2718            }
2719        } elseif ($s == 'cc3') {
2720            $ts1 = TsumegoUtil::collectTsumegosFromSet(186);
2721            $ts2 = TsumegoUtil::collectTsumegosFromSet(187);
2722            $ts3 = TsumegoUtil::collectTsumegosFromSet(196);
2723            $ts4 = TsumegoUtil::collectTsumegosFromSet(203);
2724            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2725            $tsCount = count($ts);
2726            for ($i = 0; $i < $tsCount; $i++) {
2727                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2728            }
2729            $uts = $this->TsumegoStatus->find('all', [
2730                'conditions' => [
2731                    'user_id' => Auth::getUserID(),
2732                    'tsumego_id' => $tsIds,
2733                ],
2734            ]);
2735            if (!$uts) {
2736                $uts = [];
2737            }
2738            $counter = 0;
2739            $utsCount = count($uts);
2740            for ($j = 0; $j < $utsCount; $j++) {
2741                for ($k = 0; $k < $tsCount; $k++) {
2742                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2743                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2744                        $counter++;
2745                    }
2746                }
2747            }
2748            if ($counter == count($ts)) {
2749                $completed = $s;
2750            }
2751        } elseif ($s == '1000w1') {
2752            $ts1 = TsumegoUtil::collectTsumegosFromSet(190);
2753            $ts2 = TsumegoUtil::collectTsumegosFromSet(193);
2754            $ts3 = TsumegoUtil::collectTsumegosFromSet(198);
2755            $ts = array_merge($ts1, $ts2, $ts3);
2756            $tsCount = count($ts);
2757            for ($i = 0; $i < $tsCount; $i++) {
2758                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2759            }
2760            $uts = $this->TsumegoStatus->find('all', [
2761                'conditions' => [
2762                    'user_id' => Auth::getUserID(),
2763                    'tsumego_id' => $tsIds,
2764                ],
2765            ]);
2766            if (!$uts) {
2767                $uts = [];
2768            }
2769            $counter = 0;
2770            $utsCount = count($uts);
2771            for ($j = 0; $j < $utsCount; $j++) {
2772                for ($k = 0; $k < $tsCount; $k++) {
2773                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2774                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2775                        $counter++;
2776                    }
2777                }
2778            }
2779            if ($counter == count($ts)) {
2780                $completed = $s;
2781            }
2782        } elseif ($s == '1000w2') {
2783            $ts = TsumegoUtil::collectTsumegosFromSet(216);
2784            $tsCount = count($ts);
2785            for ($i = 0; $i < $tsCount; $i++) {
2786                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2787            }
2788            $uts = $this->TsumegoStatus->find('all', [
2789                'conditions' => [
2790                    'user_id' => Auth::getUserID(),
2791                    'tsumego_id' => $tsIds,
2792                ],
2793            ]);
2794            if (!$uts) {
2795                $uts = [];
2796            }
2797            $counter = 0;
2798            $utsCount = count($uts);
2799            for ($j = 0; $j < $utsCount; $j++) {
2800                for ($k = 0; $k < $tsCount; $k++) {
2801                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2802                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2803                        $counter++;
2804                    }
2805                }
2806            }
2807            if ($counter == count($ts)) {
2808                $completed = $s;
2809            }
2810        }
2811
2812        $achievementId = 92;
2813        if ($completed == 'cc1' && !isset($existingAs[$achievementId])) {
2814            $as['AchievementStatus']['achievement_id'] = $achievementId;
2815            ClassRegistry::init('AchievementStatus')->create();
2816            ClassRegistry::init('AchievementStatus')->save($as);
2817            array_push($updated, $achievementId);
2818        }
2819        $achievementId = 93;
2820        if ($completed == 'cc2' && !isset($existingAs[$achievementId])) {
2821            $as['AchievementStatus']['achievement_id'] = $achievementId;
2822            ClassRegistry::init('AchievementStatus')->create();
2823            ClassRegistry::init('AchievementStatus')->save($as);
2824            array_push($updated, $achievementId);
2825        }
2826        $achievementId = 94;
2827        if ($completed == 'cc3' && !isset($existingAs[$achievementId])) {
2828            $as['AchievementStatus']['achievement_id'] = $achievementId;
2829            ClassRegistry::init('AchievementStatus')->create();
2830            ClassRegistry::init('AchievementStatus')->save($as);
2831            array_push($updated, $achievementId);
2832        }
2833        $achievementId = 95;
2834        if ($completed == '1000w1' && !isset($existingAs[$achievementId])) {
2835            $as['AchievementStatus']['achievement_id'] = $achievementId;
2836            ClassRegistry::init('AchievementStatus')->create();
2837            ClassRegistry::init('AchievementStatus')->save($as);
2838            array_push($updated, $achievementId);
2839        }
2840        $achievementId = 115;
2841        if ($completed == '1000w2' && !isset($existingAs[$achievementId])) {
2842            $as['AchievementStatus']['achievement_id'] = $achievementId;
2843            ClassRegistry::init('AchievementStatus')->create();
2844            ClassRegistry::init('AchievementStatus')->save($as);
2845            array_push($updated, $achievementId);
2846        }
2847        $updatedCount = count($updated);
2848        for ($i = 0; $i < $updatedCount; $i++) {
2849            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2850            $updated[$i] = [];
2851            $updated[$i][0] = $a['Achievement']['name'];
2852            $updated[$i][1] = $a['Achievement']['description'];
2853            $updated[$i][2] = $a['Achievement']['image'];
2854            $updated[$i][3] = $a['Achievement']['color'];
2855            $updated[$i][4] = $a['Achievement']['xp'];
2856            $updated[$i][5] = $a['Achievement']['id'];
2857        }
2858
2859        return $updated;
2860    }
2861
2862    protected function checkSetAchievements($sid = null) {
2863        $this->loadModel('Set');
2864        $this->loadModel('Tsumego');
2865        $this->loadModel('Achievement');
2866        $this->loadModel('AchievementStatus');
2867        $this->loadModel('AchievementCondition');
2868
2869        //$tNum = count($this->Tsumego->find('all', array('conditions' => array('set_id' => $sid))));
2870        $tNum = count(TsumegoUtil::collectTsumegosFromSet($sid));
2871        $s = $this->Set->findById($sid);
2872        $acA = ClassRegistry::init('AchievementCondition')->find('first', [
2873            'order' => 'value DESC',
2874            'conditions' => [
2875                'set_id' => $sid,
2876                'user_id' => Auth::getUserID(),
2877                'category' => '%',
2878            ],
2879        ]);
2880        if (!$acA) {
2881            return [];
2882        }
2883        $acS = ClassRegistry::init('AchievementCondition')->find('first', [
2884            'order' => 'value ASC',
2885            'conditions' => [
2886                'set_id' => $sid,
2887                'user_id' => Auth::getUserID(),
2888                'category' => 's',
2889            ],
2890        ]);
2891        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2892        if (!$buffer) {
2893            $buffer = [];
2894        }
2895        $existingAs = [];
2896        $bufferCount = count($buffer);
2897        for ($i = 0; $i < $bufferCount; $i++) {
2898            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2899        }
2900        $as = [];
2901        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2902        $updated = [];
2903
2904        $achievementId = 99;
2905        if ($sid == -1 && !isset($existingAs[$achievementId])) {
2906            $as['AchievementStatus']['achievement_id'] = $achievementId;
2907            ClassRegistry::init('AchievementStatus')->create();
2908            ClassRegistry::init('AchievementStatus')->save($as);
2909            array_push($updated, $achievementId);
2910        }
2911        if ($tNum >= 100) {
2912            if ($s['Set']['difficulty'] < 1300) {
2913                $achievementId = 12;
2914                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2915                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2916                    ClassRegistry::init('AchievementStatus')->create();
2917                    ClassRegistry::init('AchievementStatus')->save($as);
2918                    array_push($updated, $achievementId);
2919                }
2920                $achievementId = 13;
2921                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2922                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2923                    ClassRegistry::init('AchievementStatus')->create();
2924                    ClassRegistry::init('AchievementStatus')->save($as);
2925                    array_push($updated, $achievementId);
2926                }
2927                $achievementId = 14;
2928                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2929                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2930                    ClassRegistry::init('AchievementStatus')->create();
2931                    ClassRegistry::init('AchievementStatus')->save($as);
2932                    array_push($updated, $achievementId);
2933                }
2934                $achievementId = 24;
2935                if ($acS['AchievementCondition']['value'] < 15 && !isset($existingAs[$achievementId])) {
2936                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2937                    ClassRegistry::init('AchievementStatus')->create();
2938                    ClassRegistry::init('AchievementStatus')->save($as);
2939                    array_push($updated, $achievementId);
2940                }
2941                $achievementId = 25;
2942                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2943                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2944                    ClassRegistry::init('AchievementStatus')->create();
2945                    ClassRegistry::init('AchievementStatus')->save($as);
2946                    array_push($updated, $achievementId);
2947                }
2948                $achievementId = 26;
2949                if ($acS['AchievementCondition']['value'] < 5 && !isset($existingAs[$achievementId])) {
2950                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2951                    ClassRegistry::init('AchievementStatus')->create();
2952                    ClassRegistry::init('AchievementStatus')->save($as);
2953                    array_push($updated, $achievementId);
2954                }
2955            } elseif ($s['Set']['difficulty'] >= 1300 && $s['Set']['difficulty'] < 1500) {
2956                $achievementId = 15;
2957                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2958                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2959                    ClassRegistry::init('AchievementStatus')->create();
2960                    ClassRegistry::init('AchievementStatus')->save($as);
2961                    array_push($updated, $achievementId);
2962                }
2963                $achievementId = 16;
2964                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2965                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2966                    ClassRegistry::init('AchievementStatus')->create();
2967                    ClassRegistry::init('AchievementStatus')->save($as);
2968                    array_push($updated, $achievementId);
2969                }
2970                $achievementId = 17;
2971                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2972                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2973                    ClassRegistry::init('AchievementStatus')->create();
2974                    ClassRegistry::init('AchievementStatus')->save($as);
2975                    array_push($updated, $achievementId);
2976                }
2977                $achievementId = 27;
2978                if ($acS['AchievementCondition']['value'] < 18 && !isset($existingAs[$achievementId])) {
2979                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2980                    ClassRegistry::init('AchievementStatus')->create();
2981                    ClassRegistry::init('AchievementStatus')->save($as);
2982                    array_push($updated, $achievementId);
2983                }
2984                $achievementId = 28;
2985                if ($acS['AchievementCondition']['value'] < 13 && !isset($existingAs[$achievementId])) {
2986                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2987                    ClassRegistry::init('AchievementStatus')->create();
2988                    ClassRegistry::init('AchievementStatus')->save($as);
2989                    array_push($updated, $achievementId);
2990                }
2991                $achievementId = 29;
2992                if ($acS['AchievementCondition']['value'] < 8 && !isset($existingAs[$achievementId])) {
2993                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2994                    ClassRegistry::init('AchievementStatus')->create();
2995                    ClassRegistry::init('AchievementStatus')->save($as);
2996                    array_push($updated, $achievementId);
2997                }
2998            } elseif ($s['Set']['difficulty'] >= 1500 && $s['Set']['difficulty'] < 1700) {
2999                $achievementId = 18;
3000                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
3001                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3002                    ClassRegistry::init('AchievementStatus')->create();
3003                    ClassRegistry::init('AchievementStatus')->save($as);
3004                    array_push($updated, $achievementId);
3005                }
3006                $achievementId = 19;
3007                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
3008                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3009                    ClassRegistry::init('AchievementStatus')->create();
3010                    ClassRegistry::init('AchievementStatus')->save($as);
3011                    array_push($updated, $achievementId);
3012                }
3013                $achievementId = 20;
3014                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
3015                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3016                    ClassRegistry::init('AchievementStatus')->create();
3017                    ClassRegistry::init('AchievementStatus')->save($as);
3018                    array_push($updated, $achievementId);
3019                }
3020                $achievementId = 30;
3021                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
3022                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3023                    ClassRegistry::init('AchievementStatus')->create();
3024                    ClassRegistry::init('AchievementStatus')->save($as);
3025                    array_push($updated, $achievementId);
3026                }
3027                $achievementId = 31;
3028                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
3029                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3030                    ClassRegistry::init('AchievementStatus')->create();
3031                    ClassRegistry::init('AchievementStatus')->save($as);
3032                    array_push($updated, $achievementId);
3033                }
3034                $achievementId = 32;
3035                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
3036                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3037                    ClassRegistry::init('AchievementStatus')->create();
3038                    ClassRegistry::init('AchievementStatus')->save($as);
3039                    array_push($updated, $achievementId);
3040                }
3041            } else {
3042                $achievementId = 21;
3043                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
3044                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3045                    ClassRegistry::init('AchievementStatus')->create();
3046                    ClassRegistry::init('AchievementStatus')->save($as);
3047                    array_push($updated, $achievementId);
3048                }
3049                $achievementId = 22;
3050                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
3051                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3052                    ClassRegistry::init('AchievementStatus')->create();
3053                    ClassRegistry::init('AchievementStatus')->save($as);
3054                    array_push($updated, $achievementId);
3055                }
3056                $achievementId = 23;
3057                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
3058                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3059                    ClassRegistry::init('AchievementStatus')->create();
3060                    ClassRegistry::init('AchievementStatus')->save($as);
3061                    array_push($updated, $achievementId);
3062                }
3063                $achievementId = 33;
3064                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
3065                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3066                    ClassRegistry::init('AchievementStatus')->create();
3067                    ClassRegistry::init('AchievementStatus')->save($as);
3068                    array_push($updated, $achievementId);
3069                }
3070                $achievementId = 34;
3071                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
3072                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3073                    ClassRegistry::init('AchievementStatus')->create();
3074                    ClassRegistry::init('AchievementStatus')->save($as);
3075                    array_push($updated, $achievementId);
3076                }
3077                $achievementId = 35;
3078                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
3079                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3080                    ClassRegistry::init('AchievementStatus')->create();
3081                    ClassRegistry::init('AchievementStatus')->save($as);
3082                    array_push($updated, $achievementId);
3083                }
3084            }
3085            $achievementId = 46;
3086            if ($acA['AchievementCondition']['value'] >= 100) {
3087                $ac100 = ClassRegistry::init('AchievementCondition')->find('all', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => '%', 'value >=' => 100]]);
3088                if (!$ac100) {
3089                    $ac100 = [];
3090                }
3091                $ac100counter = 0;
3092                $ac100Count = count($ac100);
3093                for ($j = 0; $j < $ac100Count; $j++) {
3094                    if (count(TsumegoUtil::collectTsumegosFromSet($ac100[$j]['AchievementCondition']['set_id'])) >= 100) {
3095                        $ac100counter++;
3096                    }
3097                }
3098                $as100 = ClassRegistry::init('AchievementStatus')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'achievement_id' => $achievementId]]);
3099                if ($as100 == null) {
3100                    $as['AchievementStatus']['achievement_id'] = $achievementId;
3101                    $as['AchievementStatus']['value'] = 1;
3102                    ClassRegistry::init('AchievementStatus')->create();
3103                    ClassRegistry::init('AchievementStatus')->save($as);
3104                    array_push($updated, $achievementId);
3105                } elseif ($as100['AchievementStatus']['value'] != $ac100counter) {
3106                    $as100['AchievementStatus']['value'] = $ac100counter;
3107                    ClassRegistry::init('AchievementStatus')->save($as100);
3108                    array_push($updated, $achievementId);
3109                }
3110            }
3111        }
3112        $updatedCount = count($updated);
3113        for ($i = 0; $i < $updatedCount; $i++) {
3114            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
3115            $updated[$i] = [];
3116            $updated[$i][0] = $a['Achievement']['name'];
3117            $updated[$i][1] = $a['Achievement']['description'];
3118            $updated[$i][2] = $a['Achievement']['image'];
3119            $updated[$i][3] = $a['Achievement']['color'];
3120            $updated[$i][4] = $a['Achievement']['xp'];
3121            $updated[$i][5] = $a['Achievement']['id'];
3122        }
3123
3124        return $updated;
3125    }
3126
3127    public static function getXPJump($lvl = null): int {
3128        if ($lvl >= 102) {
3129            return 0;
3130        }
3131        if ($lvl == 101) {
3132            return 1150;
3133        }
3134        if ($lvl == 100) {
3135            return 50000;
3136        }
3137        if ($lvl >= 70) {
3138            return 150;
3139        }
3140        if ($lvl >= 40) {
3141            return 100;
3142        }
3143        if ($lvl >= 20) {
3144            return 50;
3145        }
3146        if ($lvl >= 12) {
3147            return 25;
3148        }
3149
3150        return 10;
3151    }
3152
3153    public static function getHealth($lvl = null): int {
3154        if ($lvl >= 100) {
3155            return 30;
3156        }
3157        if ($lvl >= 95) {
3158            return 29;
3159        }
3160        if ($lvl >= 90) {
3161            return 28;
3162        }
3163        if ($lvl >= 85) {
3164            return 27;
3165        }
3166        if ($lvl >= 80) {
3167            return 26;
3168        }
3169        if ($lvl >= 75) {
3170            return 25;
3171        }
3172        if ($lvl >= 70) {
3173            return 24;
3174        }
3175        if ($lvl >= 65) {
3176            return 23;
3177        }
3178        if ($lvl >= 60) {
3179            return 22;
3180        }
3181        if ($lvl >= 55) {
3182            return 21;
3183        }
3184        if ($lvl >= 50) {
3185            return 20;
3186        }
3187        if ($lvl >= 45) {
3188            return 19;
3189        }
3190        if ($lvl >= 40) {
3191            return 18;
3192        }
3193        if ($lvl >= 35) {
3194            return 17;
3195        }
3196        if ($lvl >= 30) {
3197            return 16;
3198        }
3199        if ($lvl >= 25) {
3200            return 15;
3201        }
3202        if ($lvl >= 20) {
3203            return 14;
3204        }
3205        if ($lvl >= 15) {
3206            return 13;
3207        }
3208        if ($lvl >= 10) {
3209            return 12;
3210        }
3211        if ($lvl >= 4) {
3212            return 11;
3213        }
3214
3215        return 10;
3216    }
3217
3218    public static function updateXP($userID, $achievementData): void {
3219        $xpBonus = 0;
3220        $aCount = count($achievementData);
3221        for ($i = 0; $i < $aCount; $i++) {
3222            $xpBonus += $achievementData[$i][4];
3223        }
3224        $u = ClassRegistry::init('User')->findById($userID);
3225        $jumps = [];
3226        $xStart = 40;
3227
3228        for ($i = 1; $i < 102; $i++) {
3229            if ($i == 101) {
3230                $j = 1150;
3231            } elseif ($i == 100) {
3232                $j = 50000;
3233            } elseif ($i >= 70) {
3234                $j = 150;
3235            } elseif ($i >= 40) {
3236                $j = 100;
3237            } elseif ($i >= 20) {
3238                $j = 50;
3239            } elseif ($i >= 12) {
3240                $j = 25;
3241            } else {
3242                $j = 10;
3243            }
3244            $xStart += $j;
3245            $jumps[$i] = $xStart;
3246        }
3247        $next = 0;
3248        $uLevel = $u['User']['level'];
3249        $uXp = $u['User']['xp'];
3250
3251        if ($uLevel < 101) {
3252            $currentJump = $jumps[$uLevel];
3253        } else {
3254            $currentJump = 60000;
3255        }
3256
3257        $firstJump = $currentJump;
3258
3259        if ($uXp + $xpBonus >= $currentJump) {
3260            $next = $uXp + $xpBonus - $currentJump;
3261            $uLevel++;
3262            if ($uLevel < 101) {
3263                $currentJump = $jumps[$uLevel];
3264            } else {
3265                $currentJump = 60000;
3266            }
3267        }
3268        while ($next >= $currentJump) {
3269            $next = $next - $currentJump;
3270            $uLevel++;
3271            if ($uLevel < 101) {
3272                $currentJump = $jumps[$uLevel];
3273            } else {
3274                $currentJump = 60000;
3275            }
3276        }
3277
3278        $u['User']['level'] = $uLevel;
3279        if ($uXp + $xpBonus < $firstJump) {
3280            $u['User']['xp'] += $xpBonus;
3281        } else {
3282            $u['User']['xp'] = $next;
3283        }
3284        $u['User']['nextlvl'] = $currentJump;
3285
3286        ClassRegistry::init('User')->save($u);
3287    }
3288
3289    public static function getPartitionRange($amountRemaining, $collectionSize, $partition) {
3290        if ($collectionSize > 0) {
3291            $amountPartitions = floor($amountRemaining / $collectionSize) + 1;
3292        } else {
3293            $amountPartitions = 1;
3294        }
3295        if ($collectionSize > 0 && $amountRemaining % $collectionSize == 0) {
3296            $amountPartitions--;
3297        }
3298        $amountCounter = 0;
3299        $amountFrom = 0;
3300        $amountTo = $collectionSize - 1;
3301        while ($amountRemaining > $collectionSize) {
3302            if ($partition == $amountCounter) {
3303                break;
3304            }
3305            $amountRemaining -= $collectionSize;
3306            $amountCounter++;
3307            $amountFrom += $collectionSize;
3308            $amountTo += $collectionSize;
3309        }
3310        $amountTo = $amountFrom + $collectionSize - 1;
3311        if ($partition >= $amountPartitions - 1) {
3312            $amountTo = $amountFrom + $amountRemaining - 1;
3313        }
3314        $a = [];
3315        $a[0] = $amountFrom;
3316        $a[1] = $amountTo;
3317
3318        return $a;
3319    }
3320
3321    /**
3322     * @param int $uid User ID
3323     * @return void
3324     */
3325    protected function handleSearchSettings($uid) {
3326        $this->loadModel('UserContribution');
3327        $uc = $this->UserContribution->find('first', ['conditions' => ['user_id' => $uid]]);
3328        if ($uc == null) {
3329            $uc = [];
3330            $uc['UserContribution']['user_id'] = $uid;
3331            $uc['UserContribution']['added_tag'] = 0;
3332            $uc['UserContribution']['created_tag'] = 0;
3333            $uc['UserContribution']['made_proposal'] = 0;
3334            $uc['UserContribution']['reviewed'] = 0;
3335            $uc['UserContribution']['score'] = 0;
3336            $this->UserContribution->create();
3337            $this->UserContribution->save($uc);
3338        }
3339        SearchParameters::process();
3340    }
3341
3342    // @param array $u User data
3343    /**
3344     * @param array $user User data
3345     * @return void
3346     */
3347    protected function signIn(array $user) {
3348        Auth::init($user);
3349        $vs = $this->TsumegoStatus->find('first', ['conditions' => ['user_id' => $user['User']['id']], 'order' => 'created DESC']);
3350        if ($vs) {
3351            $this->Session->write('lastVisit', $vs['TsumegoStatus']['tsumego_id']);
3352        }
3353        $this->Session->write('texture', $user['User']['texture']);
3354        $this->Session->write('check1', $user['User']['id']);
3355    }
3356
3357    /**
3358     * @return void
3359     */
3360    public function beforeFilter() {
3361        $this->loadModel('User');
3362        $this->loadModel('Activate');
3363        $this->loadModel('Tsumego');
3364        $this->loadModel('TsumegoRatingAttempt');
3365        $this->loadModel('Set');
3366        $this->loadModel('TimeModeAttempt');
3367        $this->loadModel('TsumegoStatus');
3368        $this->loadModel('Comment');
3369        $this->loadModel('UserBoard');
3370        $this->loadModel('TsumegoAttempt');
3371        $this->loadModel('AdminActivity');
3372        $this->loadModel('Achievement');
3373        $this->loadModel('AchievementStatus');
3374        $this->loadModel('AchievementCondition');
3375        $this->loadModel('SetConnection');
3376        $this->loadModel('Tag');
3377        $this->loadModel('TagName');
3378        $this->loadModel('Favorite');
3379
3380        Auth::init();
3381        $this->TimeMode->init();
3382
3383        $highscoreLink = 'highscore';
3384        $lightDark = 'light';
3385        $resetCookies = false;
3386        $levelBar = 1;
3387        $lastProfileLeft = 1;
3388        $lastProfileRight = 2;
3389        $hasFavs = false;
3390
3391        if (Auth::isLoggedIn()) {
3392            if (isset($_COOKIE['addTag']) && $_COOKIE['addTag'] != 0 && $this->Session->read('page') != 'set') {
3393                $newAddTag = explode('-', $_COOKIE['addTag']);
3394                $tagId = $newAddTag[0];
3395                $newTagName = $this->TagName->find('first', ['conditions' => ['name' => str_replace($tagId . '-', '', $_COOKIE['addTag'])]]);
3396                if ($newTagName) {
3397                    $saveTag = [];
3398                    $saveTag['Tag']['tag_name_id'] = $newTagName['TagName']['id'];
3399                    $saveTag['Tag']['tsumego_id'] = $tagId;
3400                    $saveTag['Tag']['user_id'] = Auth::getUserID();
3401                    $saveTag['Tag']['approved'] = 0;
3402                    $this->Tag->save($saveTag);
3403                }
3404                $this->set('removeCookie', 'addTag');
3405            }
3406            if (isset($_COOKIE['z_sess']) && $_COOKIE['z_sess'] != 0
3407            && strlen($_COOKIE['z_sess']) > 5) {
3408                Auth::getUser()['_sessid'] = $_COOKIE['z_sess'];
3409                Auth::saveUser();
3410            }
3411            if (Auth::getUser()['lastHighscore'] == 1) {
3412                $highscoreLink = 'highscore';
3413            } elseif (Auth::getUser()['lastHighscore'] == 2) {
3414                $highscoreLink = 'rating';
3415            } elseif (Auth::getUser()['lastHighscore'] == 3) {
3416                $highscoreLink = 'leaderboard';
3417            } elseif (Auth::getUser()['lastHighscore'] == 4) {
3418                $highscoreLink = 'highscore3';
3419            }
3420
3421            if (isset($_COOKIE['lastMode']) && $_COOKIE['lastMode'] != 0) {
3422                Auth::getUser()['lastMode'] = $_COOKIE['lastMode'];
3423                Auth::saveUser();
3424            }
3425            if (isset($_COOKIE['sound']) && $_COOKIE['sound'] != '0') {
3426                Auth::getUser()['sound'] = $_COOKIE['sound'];
3427                Auth::saveUser();
3428                unset($_COOKIE['sound']);
3429            }
3430            $this->set('ac', true);
3431            $this->set('user', Auth::getUser());
3432        }
3433
3434        if (isset($_COOKIE['lightDark']) && $_COOKIE['lightDark'] != '0') {
3435            $lightDark = $_COOKIE['lightDark'];
3436            if (Auth::isLoggedIn()) {
3437                // Convert string to integer for database storage
3438                $lightDarkInt = ($lightDark === 'light') ? 0 : 2;
3439                Auth::getUser()['lastLight'] = $lightDarkInt;
3440            }
3441        } elseif (Auth::isLoggedIn()) {
3442            if (Auth::getUser()['lastLight'] == 0
3443            || Auth::getUser()['lastLight'] == 1) {
3444                $lightDark = 'light';
3445            } else {
3446                $lightDark = 'dark';
3447            }
3448        }
3449
3450        if (Auth::isLoggedIn()) {
3451            $this->handleSearchSettings(Auth::getUserID());
3452            $favx = $this->Favorite->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
3453            if (!$favx) {
3454                $favx = [];
3455            }
3456            if (count($favx) > 0) {
3457                $hasFavs = true;
3458            }
3459            if (isset($_COOKIE['levelBar']) && $_COOKIE['levelBar'] != '0') {
3460                $levelBar = $_COOKIE['levelBar'];
3461                Auth::getUser()['levelBar'] = $levelBar;
3462            } elseif (Auth::getUser()['levelBar'] == 0
3463          || Auth::getUser()['levelBar'] == 'level') {
3464                $levelBar = 1;
3465            } else {
3466                $levelBar = 2;
3467            }
3468
3469            if (isset($_COOKIE['lastProfileLeft']) && $_COOKIE['lastProfileLeft'] != '0') {
3470                $lastProfileLeft = $_COOKIE['lastProfileLeft'];
3471                Auth::getUser()['lastProfileLeft'] = $lastProfileLeft;
3472            } else {
3473                $lastProfileLeft = Auth::getUser()['lastProfileLeft'];
3474                if ($lastProfileLeft == 0) {
3475                    $lastProfileLeft = 1;
3476                }
3477            }
3478            if (isset($_COOKIE['lastProfileRight']) && $_COOKIE['lastProfileRight'] != '0') {
3479                $lastProfileRight = $_COOKIE['lastProfileRight'];
3480                Auth::getUser()['lastProfileRight'] = $lastProfileRight;
3481            } else {
3482                $lastProfileRight = Auth::getUser()['lastProfileRight'];
3483                if ($lastProfileRight == 0) {
3484                    $lastProfileRight = 1;
3485                }
3486            }
3487        }
3488        $mode = 1;
3489        if (isset($_COOKIE['mode']) && $_COOKIE['mode'] != '0') {
3490            if ($_COOKIE['mode'] == 1) {
3491                $mode = 1;
3492            } else {
3493                $mode = 2;
3494            }
3495        }
3496
3497        if (Auth::isLoggedIn() && Auth::getUser()['mode'] == 2) {
3498            $mode = 2;
3499        }
3500
3501        if ($_COOKIE['sprint'] != 1) {
3502            $this->updateSprintCondition();
3503        }
3504        $correctSolveAttempt = false;
3505
3506        if (Auth::isLoggedIn()) {
3507            if (isset($_COOKIE['revelation']) && $_COOKIE['revelation'] != 0) {
3508                Auth::getUser()['revelation'] -= 1;
3509            }
3510
3511            $this->PlayResultProcessor->checkPreviousPlay($this->TimeMode);
3512
3513            if (isset($_COOKIE['noScore']) && isset($_COOKIE['noPreId'])) {
3514                if ($_COOKIE['noScore'] != '0' && $_COOKIE['noPreId'] != '0') {
3515                    //$previosTsumegoX = $this->Tsumego->findById($_COOKIE['noPreId']);
3516                    //$previosTsumegoXsc = $this->SetConnection->find('first', array('conditions' => array('tsumego_id' => $_COOKIE['noPreId'])));
3517                    //$scoreArrX = explode('-', $this->decrypt($_COOKIE['noScore']));
3518
3519                    $utPreX = $this->TsumegoStatus->find('first', ['conditions' => ['tsumego_id' => $_COOKIE['noPreId'], 'user_id' => Auth::getUserID()]]);
3520                    if ($utPreX == null) {
3521                        $utPreX['TsumegoStatus'] = [];
3522                        $utPreX['TsumegoStatus']['user_id'] = Auth::getUserID();
3523                        $utPreX['TsumegoStatus']['tsumego_id'] = $_COOKIE['noPreId'];
3524                    }
3525                    if ($utPreX['TsumegoStatus']['status'] == 'W') {
3526                        $utPreX['TsumegoStatus']['status'] = 'C';
3527                    } else {
3528                        $utPreX['TsumegoStatus']['status'] = 'S';
3529                    }
3530                    $utPreX['TsumegoStatus']['created'] = date('Y-m-d H:i:s');
3531                    //$this->TsumegoStatus->save($utPreX);
3532                    //$sessionUts = $this->Session->read('loggedInUser.uts');
3533                    /*if (!$sessionUts) {
3534                    $sessionUts = [];
3535                    }
3536                    $sessionUts[$utPreX['TsumegoStatus']['tsumego_id']] = $utPreX['TsumegoStatus']['status'];
3537                    $this->Session->write('loggedInUser.uts', $sessionUts);*/
3538                }
3539            }
3540        }
3541        $boardNames = [];
3542        $enabledBoards = [];
3543        $boardPositions = [];
3544
3545        $boardNames[1] = 'Pine';
3546        $boardNames[2] = 'Ash';
3547        $boardNames[3] = 'Maple';
3548        $boardNames[4] = 'Shin Kaya';
3549        $boardNames[5] = 'Birch';
3550        $boardNames[6] = 'Wenge';
3551        $boardNames[7] = 'Walnut';
3552        $boardNames[8] = 'Mahogany';
3553        $boardNames[9] = 'Blackwood';
3554        $boardNames[10] = 'Marble 1';
3555        $boardNames[11] = 'Marble 2';
3556        $boardNames[12] = 'Marble 3';
3557        $boardNames[13] = 'Tibet Spruce';
3558        $boardNames[14] = 'Marble 4';
3559        $boardNames[15] = 'Marble 5';
3560        $boardNames[16] = 'Quarry 1';
3561        $boardNames[17] = 'Flowers';
3562        $boardNames[18] = 'Nova';
3563        $boardNames[19] = 'Spring';
3564        $boardNames[20] = 'Moon';
3565        $boardNames[21] = 'Apex';
3566        $boardNames[22] = 'Gold 1';
3567        $boardNames[23] = 'Amber';
3568        $boardNames[24] = 'Marble 6';
3569        $boardNames[25] = 'Marble 7';
3570        $boardNames[26] = 'Marble 8';
3571        $boardNames[27] = 'Marble 9';
3572        $boardNames[28] = 'Marble 10';
3573        $boardNames[29] = 'Jade';
3574        $boardNames[30] = 'Quarry 2';
3575        $boardNames[31] = 'Black Bricks';
3576        $boardNames[32] = 'Wallpaper 1';
3577        $boardNames[33] = 'Wallpaper 2';
3578        $boardNames[34] = 'Gold & Gray';
3579        $boardNames[35] = 'Gold & Pink';
3580        $boardNames[36] = 'Veil';
3581        $boardNames[37] = 'Tiles';
3582        $boardNames[38] = 'Mars';
3583        $boardNames[39] = 'Pink Cloud';
3584        $boardNames[40] = 'Reptile';
3585        $boardNames[41] = 'Mezmerizing';
3586        $boardNames[42] = 'Magenta Sky';
3587        $boardNames[43] = 'Tsumego Hero';
3588        $boardNames[44] = 'Pretty';
3589        $boardNames[45] = 'Hunting';
3590        $boardNames[46] = 'Haunted';
3591        $boardNames[47] = 'Carnage';
3592        $boardNames[48] = 'Blind Spot';
3593        $boardNames[49] = 'Giants';
3594        $boardNames[50] = 'Gems';
3595        $boardNames[51] = 'Grandmaster';
3596        $boardPositions[1] = [1, 'texture1', 'black34.png', 'white34.png'];
3597        $boardPositions[2] = [2, 'texture2', 'black34.png', 'white34.png'];
3598        $boardPositions[3] = [3, 'texture3', 'black34.png', 'white34.png'];
3599        $boardPositions[4] = [4, 'texture4', 'black.png', 'white.png'];
3600        $boardPositions[5] = [5, 'texture5', 'black34.png', 'white34.png'];
3601        $boardPositions[6] = [6, 'texture6', 'black.png', 'white.png'];
3602        $boardPositions[7] = [7, 'texture7', 'black34.png', 'white34.png'];
3603        $boardPositions[8] = [8, 'texture8', 'black.png', 'white.png'];
3604        $boardPositions[9] = [9, 'texture9', 'black.png', 'white.png'];
3605        $boardPositions[10] = [10, 'texture10', 'black34.png', 'white34.png'];
3606        $boardPositions[11] = [11, 'texture11', 'black34.png', 'white34.png'];
3607        $boardPositions[12] = [12, 'texture12', 'black34.png', 'white34.png'];
3608        $boardPositions[13] = [13, 'texture13', 'black34.png', 'white34.png'];
3609        $boardPositions[14] = [14, 'texture14', 'black34.png', 'white34.png'];
3610        $boardPositions[15] = [15, 'texture15', 'black.png', 'white.png'];
3611        $boardPositions[16] = [16, 'texture16', 'black34.png', 'white34.png'];
3612        $boardPositions[17] = [17, 'texture17', 'black34.png', 'white34.png'];
3613        $boardPositions[18] = [18, 'texture18', 'black.png', 'white.png'];
3614        $boardPositions[19] = [19, 'texture19', 'black34.png', 'white34.png'];
3615        $boardPositions[20] = [20, 'texture20', 'black34.png', 'white34.png'];
3616        $boardPositions[21] = [33, 'texture33', 'black34.png', 'white34.png'];
3617        $boardPositions[22] = [21, 'texture21', 'black.png', 'whiteKo.png'];
3618        $boardPositions[23] = [22, 'texture22', 'black34.png', 'white34.png'];
3619        $boardPositions[24] = [34, 'texture34', 'black.png', 'white.png'];
3620        $boardPositions[25] = [35, 'texture35', 'black34.png', 'white34.png'];
3621        $boardPositions[26] = [36, 'texture36', 'black.png', 'white.png'];
3622        $boardPositions[27] = [37, 'texture37', 'black34.png', 'white34.png'];
3623        $boardPositions[28] = [38, 'texture38', 'black38.png', 'white34.png'];
3624        $boardPositions[29] = [39, 'texture39', 'black.png', 'white.png'];
3625        $boardPositions[30] = [40, 'texture40', 'black34.png', 'white34.png'];
3626        $boardPositions[31] = [41, 'texture41', 'black34.png', 'white34.png'];
3627        $boardPositions[32] = [42, 'texture42', 'black34.png', 'white42.png'];
3628        $boardPositions[33] = [43, 'texture43', 'black34.png', 'white42.png'];
3629        $boardPositions[34] = [44, 'texture44', 'black34.png', 'white34.png'];
3630        $boardPositions[35] = [45, 'texture45', 'black34.png', 'white42.png'];
3631        $boardPositions[36] = [47, 'texture47', 'black34.png', 'white34.png'];
3632        $boardPositions[37] = [48, 'texture48', 'black34.png', 'white34.png'];
3633        $boardPositions[38] = [49, 'texture49', 'black.png', 'white.png'];
3634        $boardPositions[39] = [50, 'texture50', 'black34.png', 'white34.png'];
3635        $boardPositions[40] = [51, 'texture51', 'black34.png', 'white34.png'];
3636        $boardPositions[41] = [52, 'texture52', 'black34.png', 'white34.png'];
3637        $boardPositions[42] = [53, 'texture53', 'black34.png', 'white34.png'];
3638        $boardPositions[43] = [54, 'texture54', 'black54.png', 'white54.png'];
3639        $boardPositions[44] = [23, 'texture23', 'black.png', 'whiteFlower.png'];
3640        $boardPositions[45] = [24, 'texture24', 'black24.png', 'white24.png'];
3641        $boardPositions[46] = [25, 'texture25', 'blackGhost.png', 'white.png'];
3642        $boardPositions[47] = [26, 'texture26', 'blackInvis.png', 'whiteCarnage.png'];
3643        $boardPositions[48] = [27, 'texture27', 'black27.png', 'white27.png'];
3644        $boardPositions[49] = [28, 'texture28', 'blackGiant.png', 'whiteKo.png'];
3645        $boardPositions[50] = [29, 'texture29', 'blackKo.png', 'whiteKo.png'];
3646        $boardPositions[51] = [30, 'texture55', 'blackGalaxy.png', 'whiteGalaxy.png'];
3647
3648        $boardCount = 51;
3649
3650        if ($this->Session->check('texture') || (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0')) {
3651            $splitCookie = [];
3652            if (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0') {
3653                $splitCookie = str_split($_COOKIE['texture']);
3654                $textureCookies = $_COOKIE['texture'];
3655                Auth::getUser()['texture'] = $this->Session->read('texture');
3656                $this->Session->write('texture', $_COOKIE['texture']);
3657                $this->set('textureCookies', $textureCookies);
3658            } else {
3659                if (Auth::isLoggedIn()) {
3660                    $this->Session->write('texture', Auth::getUser()['texture']);
3661                }
3662                $textureCookies = $this->Session->read('texture');
3663                $splitTextureCookies = str_split($textureCookies);
3664                $splitTextureCookiesCount = count($splitTextureCookies);
3665                for ($i = 0; $i < $splitTextureCookiesCount; $i++) {
3666                    if ($splitTextureCookies[$i] == 2) {
3667                        $enabledBoards[$i + 1] = 'checked';
3668                    } else {
3669                        $enabledBoards[$i + 1] = '';
3670                    }
3671                }
3672            }
3673
3674            $splitCookieCount = count($splitCookie);
3675            for ($i = 0; $i < $splitCookieCount; $i++) {
3676                if ($splitCookie[$i] == 2) {
3677                    $enabledBoards[$i + 1] = 'checked';
3678                } else {
3679                    $enabledBoards[$i + 1] = '';
3680                }
3681            }
3682            if (Auth::isLoggedIn()) {
3683                Auth::saveUser();
3684            }
3685        }
3686
3687        if (!$this->Session->check('texture')) {
3688            $this->Session->write('texture', '222222221111111111111111111111111111111111111111111');
3689            $enabledBoards[1] = 'checked';
3690            $enabledBoards[2] = 'checked';
3691            $enabledBoards[3] = 'checked';
3692            $enabledBoards[4] = 'checked';
3693            $enabledBoards[5] = 'checked';
3694            $enabledBoards[6] = 'checked';
3695            $enabledBoards[7] = 'checked';
3696            $enabledBoards[8] = 'checked';
3697            $enabledBoards[9] = '';
3698            $enabledBoards[10] = '';
3699            $enabledBoards[11] = '';
3700            $enabledBoards[12] = '';
3701            $enabledBoards[13] = '';
3702            $enabledBoards[14] = '';
3703            $enabledBoards[15] = '';
3704            $enabledBoards[16] = '';
3705            $enabledBoards[17] = '';
3706            $enabledBoards[18] = '';
3707            $enabledBoards[19] = '';
3708            $enabledBoards[20] = '';
3709            $enabledBoards[21] = '';
3710            $enabledBoards[22] = '';
3711            $enabledBoards[23] = '';
3712            $enabledBoards[24] = '';
3713            $enabledBoards[25] = '';
3714            $enabledBoards[26] = '';
3715            $enabledBoards[27] = '';
3716            $enabledBoards[28] = '';
3717            $enabledBoards[29] = '';
3718            $enabledBoards[30] = '';
3719            $enabledBoards[31] = '';
3720            $enabledBoards[32] = '';
3721            $enabledBoards[33] = '';
3722            $enabledBoards[34] = '';
3723            $enabledBoards[35] = '';
3724            $enabledBoards[36] = '';
3725            $enabledBoards[37] = '';
3726            $enabledBoards[38] = '';
3727            $enabledBoards[39] = '';
3728            $enabledBoards[40] = '';
3729            $enabledBoards[41] = '';
3730            $enabledBoards[42] = '';
3731            $enabledBoards[43] = '';
3732            $enabledBoards[44] = '';
3733            $enabledBoards[45] = '';
3734            $enabledBoards[46] = '';
3735            $enabledBoards[47] = '';
3736            $enabledBoards[48] = '';
3737            $enabledBoards[49] = '';
3738            $enabledBoards[50] = '';
3739            $enabledBoards[51] = '';
3740        }
3741        $achievementUpdate = [];
3742        if ($this->Session->check('initialLoading')) {
3743            $achievementUpdate1 = $this->checkLevelAchievements();
3744            $achievementUpdate2 = $this->checkProblemNumberAchievements();
3745            $achievementUpdate3 = $this->checkRatingAchievements();
3746            $achievementUpdate4 = $this->checkTimeModeAchievements();
3747            $achievementUpdate5 = $this->checkDanSolveAchievements();
3748            $achievementUpdate = array_merge(
3749                $achievementUpdate1 ?: [],
3750                $achievementUpdate2 ?: [],
3751                $achievementUpdate3 ?: [],
3752                $achievementUpdate4 ?: [],
3753                $achievementUpdate5 ?: [],
3754            );
3755            $this->Session->delete('initialLoading');
3756        }
3757
3758        if (count($achievementUpdate) > 0) {
3759            $this->updateXP(Auth::getUserID(), $achievementUpdate);
3760        }
3761
3762        $nextDay = new DateTime('tomorrow');
3763        if (Auth::isLoggedIn()) {
3764            Auth::getUser()['name'] = $this->checkPicture(Auth::getUser());
3765            $this->set('user', Auth::getUser());
3766        }
3767        $this->set('mode', $mode);
3768        $this->set('nextDay', $nextDay->format('m/d/Y'));
3769        $this->set('boardNames', $boardNames);
3770        $this->set('enabledBoards', $enabledBoards);
3771        $this->set('boardPositions', $boardPositions);
3772        $this->set('highscoreLink', $highscoreLink);
3773        $this->set('achievementUpdate', $achievementUpdate);
3774        $this->set('lightDark', $lightDark);
3775        $this->set('levelBar', $levelBar);
3776        $this->set('lastProfileLeft', $lastProfileLeft);
3777        $this->set('lastProfileRight', $lastProfileRight);
3778        $this->set('resetCookies', $resetCookies);
3779        $this->set('hasFavs', $hasFavs);
3780    }
3781
3782    public function afterFilter() {}
3783}